使用__slots__
使用原因
python是动态语言,可以动态的对已经定义好的对象进行增加,修改属性操作
作用
在类中定义,采用tuple限制了该类的动态属性定义
实例
class Student(object):
__slots__ = ('name', 'age')
因为score没有在__slots__中定义,所以实例化Student,动态添加score时出现“AttributeError”错误
>>> s = Student()
>>> s.name = 'syy'
>>> s.age = 30
>>> s.score = 99
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'
==注意:==如子类继承了有__slots__定义的父类,且没有在子类中实现__slots__,那么父类定义的__slots__不会影响子类;如果子类实现了__slots__那么子类实例化后,添加属性的限制范围为,父类和子类__slots__定义的集合
>>> class A(Student):
... pass
...
>>> g = A()
>>> g.name = 'fff'
>>> g.name
'fff'
>>> g.score = 98
>>> g.score
98
>>> class C(Student):
... __slots__ = ()
...
>>> s = C()
>>> s.name = 'sss'
>>> s.name
'sss'
>>> s.score = 89
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'score'
>>> class D(Student):
... __slots__ = ('score')
...
>>> d = D()
>>> d.score = 32
>>> d.score
32
>>> d.sxe
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'D' object has no attribute 'sxe'
>>> d.sxe = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'D' object has no attribute 'sxe'