正常情況下藏姐,當(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é)果
但是问畅,給一個(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(88)
>>> s2.score
88
通常情況下,上面的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
屬性捅膘。
為了達(dá)到限制的目的添祸,Python允許在定義class的時(shí)候,定義一個(gè)特殊的__slots__
變量寻仗,來(lái)限制該class實(shí)例能添加的屬性:
class Student(object):
__slots__ = ('name', 'age') #用tuple定義允許綁定的屬性名稱(chēng)
然后試試:
>>> 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'
由于score
沒(méi)有被放到__slots__
中刃泌,所以不能綁定score
屬性,試圖綁定score
將得到AttributeError
的錯(cuò)誤。
使用__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__
硝烂。