__slots__
通过__slots__
限制动态添加的属性名
添加属性
In [47]: class Person(object):
....: __slots__ = ('name', 'age')
....:
In [48]: class Person(object):
....: __slots__ = ('name', 'age')
....: def __init__(self, name):
....: self.name = name
....:
In [49]: p1 = Person('Da')
In [50]: p1.age = 21
In [51]: p1.attr = 'BJ'
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-51-45799c3a5447> in <module>()
----> 1 p1.attr = 'BJ'
AttributeError: 'Person' object has no attribute 'attr'
添加方法
In [55]: def age(self, age):
....: print('--- {}: {}---'.format(self.name, age))
....:
In [56]: p1.age = types.MethodType(age, p1)
In [57]: p1.age('18')
--- Da: 18---
In [58]: p1.add = types.MethodType(age, p1)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-58-66ffb41d95d6> in <module>()
----> 1 p1.add = types.MethodType(age, p1)
AttributeError: 'Person' object has no attribute 'add'