美文网首页
01.11 - 类的属性

01.11 - 类的属性

作者: xxxQinli | 来源:发表于2019-01-11 17:10 被阅读0次

什么是对象的属性

  • 类中的属性分为类的字段和对象属性

  • a. 对象属性 - 属性的值会因为对象不同而不一样,这种属性就应该声明为对象属性

声明在init方法中

  • 以‘self. 属性名 = 值'的方式来声明(这儿的属性就是对象属性) - 方式

  • 通过'对象.属性'的方式来使用 - 使用

  • b. 类的字段 - 属性的值不会因为对象的不同而不同,这种属性就声明成类的字段

  • 直接声明在类中,函数的外面的变量就是类的字段

  • 以’字段名 = 值‘

  • 通过类.字段的方式来使用

class Ql_Person:  # 

    num = 61

    def __init__(self, x, y):
        
        self.name = x
        self.age = y

    def ql_(self, x):  #
        
        pass
        return 

print(Ql_Person.num) # 使用类的字段

p1 = Ql_Person('张三', 18)
print(p1.name, p1.age)
 
    
# 练习:创建Dog类,有属性名字,类型,年龄
# 要求创建Dog的对象的时候,不能给年龄赋值,可以给类型赋值,也可以不用不用给类型赋值,必须给名字赋值

class Ql_Dog:  # 
    
    def __init__(self, name, type = None):
        
        self.name = name
        self.type = type
        self.age = 10
    
    def ql_eat(self, food):  #
        
        print('%s在吃%s' % (self.name, food))
        return 

dog1 = Ql_Dog('nini', 'big')
print(dog1.name, dog1.type)
print(dog1.age)
dog1.ql_eat('骨头')

# 练习:声明一个矩形类,拥有属性长和宽,拥有方法获取面积和周长

class Ql_Rect:  # 
    
    def __init__(self, x, y):
        
        self.length = x
        self.width = y

    def ql_Area(self):  #
        
        print('面积为:', (self.length * self.width))
    
    def ql_Perm(self):  #
        
        print('周长为:', (self.length*2 + self.width*2))

rect1 = Ql_Rect(10, 20)
rect1.ql_Area()
rect1.ql_Perm()


相关文章

网友评论

      本文标题:01.11 - 类的属性

      本文链接:https://www.haomeiwen.com/subject/qaoxdqtx.html