面向?qū)ο蟾呒?jí)編程1

使用slots
正常情況下,我們定義了一個(gè)class,創(chuàng)建了一個(gè)class的實(shí)例后,我們可以給該實(shí)力綁定任何屬性和方法,這就是動(dòng)態(tài)語言的靈活性。先定義class:

class Student(object):
        pass

然后嘗試給實(shí)例綁定一個(gè)屬性:

>>> s = Studnet()
>>> s.name = 'Cai'
>>> print(s.name)
Cai

還可以嘗試給實(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)行的過程中給class加上功能,這在靜態(tài)語言中很難實(shí)現(xiàn)。

使用slots

但是,如果我們想要限制實(shí)例的屬性怎么辦?比如,只允許對(duì)Student實(shí)例添加nameage屬性。
為了達(dá)到限制的目的,Python允許在定義class的時(shí)候,定義一個(gè)特殊的__slots__變量,來限制該class實(shí)例能添加的屬性:

>>> class Student(object):
...     __slots__ = ('name', 'age')    # 用tuple定義允許綁定的屬性名稱
...
>>> s = Student()    # 創(chuàng)建新的實(shí)例
>>> s.name = 'Cai'    # 綁定屬性'name'
>>> s.age = 18    # 綁定屬性'age'
>>> s.score = 99    # 綁定屬性'score'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'

由于score沒有被方法__slots__中,所以不能綁定score屬性,駛?cè)虢壎?code>score將得到AttributeError的錯(cuò)誤
使用__slots__要注意,__slots__定義的屬性僅對(duì)當(dāng)前類實(shí)例起作用,對(duì)繼承的子類是不起作用的:

>>> class GraduateStudent(Student):
...     pass
...
>>> g = GraduateStudent()
>>> g.score = 9999

除非在子類中也定義__slots__,這樣,子類實(shí)例允許定義的屬性就是自身的__slots__加上父類的__slots__

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容