Python執行個體屬性限制(__slots__)

來源:互聯網
上載者:User

標籤:class類   last   self   test   指南   port   int   父類   obj   

Python的動態綁定可以在程式啟動並執行過程中對執行個體或class加上功能,但是如果我們想要限制執行個體的屬性怎麼辦呢?更改內容請參考:Python學習指南

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

class Student(object):    pass

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

s = Student()s.name = 'Michael'print(s.name)Michael

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

def set_age(self, age):  #定義一個函數作為執行個體方法    self.age = agefrom types import MethodTypes.set_age = MethodType(set_age, s)  #給執行個體綁定一個方法s.set_age(25)s.age25

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

s2 = Student()  #建立一個新的執行個體s2.set_age(25)Traceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: 'Student' object has no attribute 'set_age'

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

def set_score(self, score):      self.score = scoreStudent.set_score = set_score

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

s.set_score(100)s.score100s2.set_score(99)s2.score99

只要在class上Binder 方法以後,執行個體就可以直接使用了。

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

使用__slots__
但是,如果我們想要限制執行個體的屬性怎麼辦?比如,只允許對Student執行個體添加 nameage實現。

為了達到限制的目的,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 "<stdin>", line 1, in <module>AttributeError: 'Student' object has no attribute 'score'>>>Student.score = 100>>>s.score100

由於‘score‘沒有被放到__slots__中,所以不能綁定score屬性,試圖綁定score將得到AttributeError的錯誤。但是可以對class類添加屬性,__slots__只是限制執行個體添加的屬性,但類屬性管不了。

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

class GraduteStudent(Student):    passg = GraduteStudent()s.score = 99

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

Python執行個體屬性限制(__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.