3. 类属性

Python 中一切皆对象,类也是一个对象,它相当于对象的工厂。

什么是类属性

类属性是类的属性,此属性属于类,不属于此类的对象(实例)。

作用:

通常用来存储该类创建的对象的共有属性。

语法

class 类名:
    类属性名 = 值  # 创建类时直接定义属性
    def 方法名(self, ...):
        ...
类名.类属性名 = 值  # 后添加类属性

示例:

class Dog:
    home = '地球'  # 创建类时直接创建属性
    def eat(self, food):
        pass

Dog.species = '动物'  # 后添加类属性

print(Dog.home)
print(Dog.eat)
print(Dog.species)

dog1 = Dog()
print(dog1.home)
print(dog1.__class__.home)

# dog1.home = '中国'
dog1.__class__.home = 'xxxxx'
print(Dog.home)

对于类属性,Dog 类和 Dog类的对象 dog1 都可以访问类的属性 home 。但对象 dog1 只有通过 __class__ 属性才能修改类属性。

类属性说明