正常情況下牺陶,當(dāng)我們定義了一個(gè)class捡需,創(chuàng)建了一個(gè)class的實(shí)例后凡蜻,我們可以給該實(shí)例綁定任何屬性和方法搭综,這就是動(dòng)態(tài)語(yǔ)言的靈活性。
## 定義class
class Student(object):
pass
## 嘗試給實(shí)例綁定一個(gè)屬性
>>> s = Student()
>>> s.name = 'Michael' # 動(dòng)態(tài)給實(shí)例綁定一個(gè)屬性
>>> print(s.name)
Michael
## 嘗試給實(shí)例綁定一個(gè)方法
>>> def set_age(self, age): # 定義一個(gè)函數(shù)作為實(shí)例方法
... self.age = age
...
>>> from types import MethodType
>>> s.set_age = MethodType(set_age, s) # 給實(shí)例綁定一個(gè)方法
>>> s.set_age(25) # 調(diào)用實(shí)例方法
>>> s.age # 測(cè)試結(jié)果
25
## 給一個(gè)實(shí)例綁定的方法划栓,對(duì)另一個(gè)實(shí)例是不起作用的
>>> s2 = Student() # 創(chuàng)建新的實(shí)例
>>> s2.set_age(25) # 嘗試調(diào)用方法
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'set_age'
## 為了給所有實(shí)例都綁定方法兑巾,可以給class綁定方法
>>> def set_score(self, score):
... self.score = score
...
>>> Student.set_score = set_score
## 給class綁定方法后,所有實(shí)例均可調(diào)用
>>> s.set_score(100)
>>> s.score
100
>>> s2.set_score(99)
>>> s2.score
99
通常情況下忠荞,上面的set_score方法可以直接定義在class中蒋歌,但動(dòng)態(tài)綁定允許我們?cè)诔绦蜻\(yùn)行的過(guò)程中動(dòng)態(tài)給class加上功能,這在靜態(tài)語(yǔ)言中很難實(shí)現(xiàn)委煤。
使用__slots__
如果我們想要限制實(shí)例的屬性怎么辦奋姿?
## 只允許對(duì)Student實(shí)例添加name和age屬性
class Student(object):
__slots__ = ('name', 'age') # 用tuple定義允許綁定的屬性名稱(chēng)
## 測(cè)試
>>> s = Student() # 創(chuàng)建新的實(shí)例
>>> 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'
使用__slots__
要注意,__slots__
定義的屬性?xún)H對(duì)當(dāng)前類(lèi)實(shí)例起作用素标,對(duì)繼承的子類(lèi)是不起作用的:
>>> class GraduateStudent(Student):
... pass
...
>>> g = GraduateStudent()
>>> g.score = 9999
除非在子類(lèi)中也定義__slots__
称诗,這樣,子類(lèi)實(shí)例允許定義的屬性就是自身的__slots__
加上父類(lèi)的__slots__
头遭。