动态添加实例属性如果随意添加属性那么封装将变得不安全了。可以通过__slots__限制添加的内容
class People:
__slots__ = ('speed') #用法__slots__ = ('你想添加的属性')
people = People()
people.speed = 100
print('people.speed:', people.speed)
打印结果:
people.speed: 100
如果你想再添加一个属性people.weight = 120
class People:
__slots__ = ('speed') #用法__slots__ = ('你想添加的属性')
people = People()
people.speed = 100
print('people.speed:', people.speed)
people.weight = 120 #想再添加一个weight属性
print('people.weight:', people.weight)
打印结果会报错:
AttributeError: ‘People’ object has no attribute ‘weight’
意思是我们需要在__slots__里再添加一个weight属性
__slots__ = ('speed', 'weight')#用法__slots__ = ('你想添加的属性')
添加之后,再打印就不会出错了,结果如下:
people.speed: 100
people.weight: 120