上一篇有提到经过动态绑定:在类外部定义方法,而后动态地给类加上新的功能,使得类的实例都能调用外部方法。
但若是要限制实例的属性,不容许动态地添加,该怎么办呢?python
为了达到限制的目的,python容许在定义class的时候,定义一个特殊的 slots 变量,来限制该class实例动态添加属性。
那使用__slot__的好处呢?code
例如:只容许对Student实例添加 name 和 age 属性。继承
>>> class Student(object): ... __slots__ = ('name','age') # 使用tuple定义容许绑定的属性名称 >>> s = Student() # 建立新的实例 >>> s.name = 'xlp' # 绑定属性name >>> s.age = 24 # 绑定属性age >>> s.score = 99 # 绑定属性score # 可是score没有放到__slots__中,因此不能绑定score属性,报错。 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute 'score'
!!!可是__slots__
定义的属性只对当前类的实例起做用,对继承的子类是不起做用的。除非在子类中也定义__slots__
。
这样子类实例容许定义的属性就是自身的__slots__
+ 父类的__slots__
限定的属性。
例如:内存
>>> class SStudent(Student): ... __slots__ = 'gender' ... >>> g = SStudent() >>> g.name = 'xxx' >>> g.score = 99 # 子类依旧能够动态绑定属性 >>> g.gender = 'Female' >>> g.teacher = 'Mrs. Wang' # 不容许绑定咯~ Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'SStudent' object has no attribute 'teacher'
子类SStudent除掉能够绑定name、age,还能够绑定定义在子类__slot__中的gender属性。
可是teacher属性没有在__slot__限制中,故不能动态绑定,会报错。input
❤ thanks for watching, keep on updating...
点个赞再走吧ast