限制__slot__
上一篇有提到通過動態綁定:在類外部定義方法,然後動態地給類加上新的功能,使得類的實例都能調用外部方法。
但如果要限制實例的屬性,不允許動態地添加,該怎麼辦呢?
爲了達到限制的目的,python允許在定義class的時候,定義一個特殊的 slots 變量,來限制該class實例動態添加屬性。
那使用__slot__的好處呢?
- 防止用戶隨意動態增加實例屬性;
- 節約內存,因爲動態綁定時屬性存儲在__dict__中;
- 更快的屬性訪問速度。
例如:只允許對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__限制中,故不能動態綁定,會報錯。
❤ thanks for watching, keep on updating...
點個贊再走吧