python允许在定义class时,定义一个特殊的__slots__变量,来限制class实例梦添加的属性。
>>> class Person(object):
__slots__ = ("name", "age")
>>> P = Person()
>>> P.name = "老王"
>>> P.age = 20
>>> P.score = 100
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
AttributeError: Person instance has no attribute 'score'
>>>
*******************************************
使用需要注意定义的属性只对当前类的实例起作用,对继承的子类不起作用。
In [67]: class Test(Person):
...: pass
...:
In [68]: t = Test()
In [69]: t.score = 100