在Python中使用__slots__方法的詳細教程

來源:互聯網
上載者:User
正常情況下,當我們定義了一個class,建立了一個class的執行個體後,我們可以給該執行個體綁定任何屬性和方法,這就是動態語言的靈活性。先定義class:

>>> class Student(object):...   pass...

然後,嘗試給執行個體綁定一個屬性:

>>> s = Student()>>> s.name = 'Michael' # 動態給執行個體綁定一個屬性>>> print s.nameMichael

還可以嘗試給執行個體綁定一個方法:

>>> def set_age(self, age): # 定義一個函數作為執行個體方法...   self.age = age...>>> from types import MethodType>>> s.set_age = MethodType(set_age, s, Student) # 給執行個體綁定一個方法>>> s.set_age(25) # 調用執行個體方法>>> s.age # 測試結果25

但是,給一個執行個體綁定的方法,對另一個執行個體是不起作用的:

>>> s2 = Student() # 建立新的執行個體>>> s2.set_age(25) # 嘗試調用方法Traceback (most recent call last): File "", line 1, in AttributeError: 'Student' object has no attribute 'set_age'

為了給所有執行個體都Binder 方法,可以給classBinder 方法:

>>> def set_score(self, score):...   self.score = score...>>> Student.set_score = MethodType(set_score, None, Student)

給classBinder 方法後,所有執行個體均可調用:

>>> s.set_score(100)>>> s.score100>>> s2.set_score(99)>>> s2.score99

通常情況下,上面的set_score方法可以直接定義在class中,但動態綁定允許我們在程式啟動並執行過程中動態給class加上功能,這在靜態語言中很難實現。
使用__slots__

但是,如果我們想要限制class的屬性怎麼辦?比如,只允許對Student執行個體添加name和age屬性。

為了達到限制的目的,Python允許在定義class的時候,定義一個特殊的__slots__變數,來限制該class能添加的屬性:

>>> class Student(object):...   __slots__ = ('name', 'age') # 用tuple定義允許綁定的屬性名稱...

然後,我們試試:

>>> s = Student() # 建立新的執行個體>>> s.name = 'Michael' # 綁定屬性'name'>>> s.age = 25 # 綁定屬性'age'>>> s.score = 99 # 綁定屬性'score'Traceback (most recent call last): File "", line 1, in AttributeError: 'Student' object has no attribute 'score'

由於'score'沒有被放到__slots__中,所以不能綁定score屬性,試圖綁定score將得到AttributeError的錯誤。

使用__slots__要注意,__slots__定義的屬性僅對當前類起作用,對繼承的子類是不起作用的:

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

除非在子類中也定義__slots__,這樣,子類允許定義的屬性就是自身的__slots__加上父類的__slots__。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.