python Descriptor (描述符)

來源:互聯網
上載者:User

標籤:static   dict   variables   entry   ted   icm   UI   always   end   

簡介:

python 描述符是新式類(繼承自object)中的語言協議,基於描述符可以提供更佳優雅的解決方案。

python的classmethod, staticmethod, property都是基於描述符建立的。

 

描述符的協議:

定義了__set__, __get__, __delete__3個方法中任何一個方法的object可以作為描述符.

 

描述符分類:

同時定義了__set__,__get__被叫做data descriptor.

只定義了__get__被叫做no-data descriptor.

 

2種描述符的區別:

 Data and non-data descriptors differ in how overrides are calculated with respect to entries in an instance’s dictionary. If an instance’s dictionary has an entry with the same name as a data descriptor, the data descriptor takes precedence. If an instance’s dictionary has an entry with the same name as a non-data descriptor, the dictionary entry takes precedence.

在 attrubuite lookup過程中 : 

如果對象屬性有與data-descriptor同名的屬性,data-descriptor優先於對象屬性.

 如果對象屬性有與no-data descriptor同名的屬性,對象屬性優先。

 

觸發描述符的調用:

A descriptor can be called directly by its method name. For example, d.__get__(obj).

Alternatively, it is more common for a descriptor to be invoked automatically upon attribute access. For example, obj.d looks up d in the dictionary of obj. If d defines the method __get__(), thend.__get__(obj) is invoked according to the precedence rules listed below.

The details of invocation depend on whether obj is an object or a class. Either way, descriptors only work for new style objects and classes. A class is new style if it is a subclass of object.

For objects, the machinery is in object.__getattribute__() which transforms b.x into type(b).__dict__[‘x‘].__get__(b, type(b)). The implementation works through a precedence chain that gives data descriptors priority over instance variables, instance variables priority over non-data descriptors, and assigns lowest priority to __getattr__() if provided

 

The important points to remember are:

  • descriptors are invoked by the __getattribute__() method
  • overriding __getattribute__() prevents automatic descriptor calls
  • __getattribute__() is only available with new style classes and objects
  • object.__getattribute__() and type.__getattribute__() make different calls to __get__().
  • data descriptors always override instance dictionaries.
  • non-data descriptors may be overridden by instance dictionaries.

 

python Descriptor (描述符)

聯繫我們

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