python中descriptor(描述器)就是這麼回事,pythondescriptor

來源:互聯網
上載者:User

python中descriptor(描述器)就是這麼回事,pythondescriptor

很多教程往往把descriptor說的很複雜,長篇大文,洋洋洒洒,結果很多人看的雲裡霧裡.

其實就一句話,對類的操作進行hook,以此控制行為.

大部分時候是用來攔截對執行個體屬性的訪問。
只要類中有__get__(), __set__(), 和 __delete__()其中之一的方法.那麼它就是一個描述器.我們想一想,對一個類進行操作,逃不開這三種方法,我們需要控制什麼操作,就hook哪個方法.
描述器不是self host的,而是寄生在其它類中.
property, classmethod, staticmethod, super的實現原理正是描述器.

說這麼多,下面用代碼展示,相信一清二楚.

#coding=utf-8class Integer(object):#Integer就是一個描述器,因為定義了__set__()方法.    def __init__(self, name):        self.name = name    def __set__(self, instance, value):#因為我們只需要對"修改屬性"這個行為進行hook,所以我們只定義__set__()方法就夠了,不用__get__()和__delete__().        if not isinstance(value, int):            raise TypeError('Expected an int')        instance.__dict__[self.name] = valueclass Point(object):    x = Integer('x')    y = Integer('y')    def __init__(self, x, y):        self.x = x        self.y = yp = Point(2, 3)p.x = 9p.x = 9.9#這句會拋出TypeError: Expected an int錯誤.這就是描述器的作用.



python中用fileno沒返迴文件描述符,問是為何?

這個是函數,你要用fileno();而不是fileno
 
初學PYTHON遇到的小問題

你開啟一個寫檔案(w), 卻嘗試用read讀取!
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.