zoukankan      html  css  js  c++  java
  • python的类和对象的创建

    最近接触到了一些面向对象编程的内容,涉及到了一些对象和类的只是,在这里复习一下,附上学习代码如下

     1 class Person:
     2     hair = 'black'      #此处定义一个类变量hair
     3     def __init__ (self, name='charlie', age = 22):
     4         #此处为Person对象增加两个实例变量
     5         self.name  = name
     6         self.age = age
     7 
     8     #d定义一个say方法
     9     def say(self, content):
    10         return content
    11 
    12 #调用person类的构造方法,返回Person的一个对象并将该对象赋值给p
    13 p = Person()
    14 #输出p的name和age两个实例变量,此时这两给变量还是默认值
    15 print(p.name,'
    ',p.age)
    16 #访问p的实例变量name,并为他重新赋值
    17 p.name = 'wind_under_the_wing'
    18 
    19 #调用p的say方法,
    20 
    21 print('hello,I am ' + p.name + ',' +  p.say('welcome to my blog'))

    __init__是构造方法,用于创建对象,某个类最少要有一种构造方法,调用该类的构造方法即可创建这个类的对象

    下面是书中的一个例子

    class Dog():
        def __init__(self,name, age):
            """初始化属性 name age"""
            self.name = name
            self.age = age
        def sit(self):
            print(self.name.title() + 'is siting now!')
        def roll_over(self):
            print(self.name.title() + 'is rolled now!')
    
    mydog = Dog('willed', 8)
    
    print("My dog's name is " + mydog.name.title() + '.' )
    print("My dog is " + str(mydog.age) + ' years old.
    ')
    
    mydog.roll_over()
    mydog.sit()
    print('
    ')
    yourdog = Dog('luck', 3)
    print("your dog'name is" + yourdog.name.title() + '.')
    print('yourdog is' + str(yourdog.age) + 'years old.')
    yourdog.sit()
    yourdog.roll_over()
  • 相关阅读:
    JDBC连接
    Ubuntu 16.04安装MySQL(5.7.18)
    AOP拦截日志报错llegalStateException: It is illegal to call this method if the current request is not in asynchronous mode
    mybatis笔记
    打扮IDEA更换主题
    简单的IDEA破解到2099年
    UML之时序图详解
    UML之类图详解
    UML之用例图详解
    spring和springboot常用注解总结
  • 原文地址:https://www.cnblogs.com/wind-under-the-wing/p/11961328.html
Copyright © 2011-2022 走看看