使用__slots__ 可以限制实例的属性
class Student(object): pass s = Student() s.name = 'Michael' s.age = 25 s.score = 99
|
这样是没有问题的,但是通过__slots__ 可以限制只能添加 name 和 age 属性
class Student(object): pass __slots__ = ('name','age')
s = Student() s.name = 'Michael' s.age = 25 s.score = 99
|
会提示
Traceback (most recent call last): File "/Users/wenjun/PycharmProjects/python2018/day01/oopdemo.py", line 11, in <module> s.score = 99 AttributeError: 'Student' object has no attribute 'score'
|
由于’score’没有被放到__slots__中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。
使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:
除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。
class Student(object): pass __slots__ = ('name','age')
class GraduateStudent(Student): pass
g = GraduateStudent() g.score = 9999
|
文章作者:阿文
版权声明:本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0 许可协议。转载请注明来自
阿文的博客!