类属性和实例属性
类属性和实例属性
类属性
设置、访问和修改的方法。
- 类属性就是类对象所拥有的属性,它被该类的所有实例对象所共有
- 类属性可以使用类对象或实例对象访问
class Dog(object):
tooth = 10 # 设置类属性
wangcai = Dog()
xiaohei = Dog()
print(Dog.tooth) # 10
print(wangcai.tooth) # 10
print(xiaohei.tooth) # 10
优点:
- 记录的某些数据始终保持一致时,则定义类属性
- 实例属性要求每个对象为其单独开辟一份内存空间来记录数据,而类属性为全类所共有,仅占用一份内存,更加节省内存空间。
修改类属性
类属性只能通过类对象修改,不能通过实例对象修改,如果通过实例对象修改类属性,表示的是创建了一个实例属性
class Dog(object):
tooth = 10 # 设置类属性
wangcai = Dog()
xiaohei = Dog()
# 修改类属性
Dog.tooth = 12
print(Dog.tooth) # 12
print(wangcai.tooth) # 12
print(xiaohei.tooth) # 12
# 不能通过对象修改属性,如果这样操作,实则是创建了一个实例属性
wangcai.tooth = 20
print(Dog.tooth) # 12
print(wangcai.tooth) # 20
print(xiaohei.tooth) # 12