class中限定绑定属性__slots__方法

使用__slots__
可是,若是咱们想要限制class的属性怎么办?好比,只容许对Student实例添加name和age属性。
为了达到限制的目的,Python容许在定义class的时候,定义一个特殊的__slots__变量,来限制该class能添加的属性:
 class Student(object):
     __slots__ = ('name', 'age') # 用tuple定义容许绑定的属性名称
而后,咱们试试:
s = Student() # 建立新的实例
s.name = 'Michael' # 绑定属性'name'
s.age = 25 # 绑定属性'age'
s.score = 99 # 绑定属性'score'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'
因为'score'没有被放到__slots__中,因此不能绑定score属性,试图绑定score将获得AttributeError的错误。
使用__slots__要注意,__slots__定义的属性仅对当前类起做用,对继承的子类是不起做用的:
>>> class GraduateStudent(Student):
...     pass
...
>>> g = GraduateStudent()
>>> g.score = 9999
除非在子类中也定义__slots__,这样,子类容许定义的属性就是自身的__slots__加上父类的__slots__。继承

相关文章
相关标签/搜索