Tekkaman

导航

 

python's descriptor

 1、实现了以下三个方法任意一个的,且作为成员变量存在的对象,就是descriptor。

  1)object.__get__(selfinstanceowner):instance是实例的引用,owner是类对象的引用。

  2)object.__set__(selfinstancevalue)

  3)object.__delete__(selfinstance)

  The descriptor must be in either the owner’s class dictionary or in the class dictionary for one of its parents

   descriptor必须是类属性(class attribute)

  参考:http://docs.python.org/2.7/reference/datamodel.html?highlight=__mro__#implementing-descriptors

 2、Invoking

     

  上图红线框部分,可以看到a.x会被转换为 type(a).__dict__['x'].__get__(a, type(a))。这说明两个问题:

    1、Class.X调用是无用的,因为会被转化为type(Class).__dict__['X'],type(Class)中显然没定义。

    2、descriptor必须是类属性。

  3、function & unbound method & bound method

  这三个东西都是同一个对象,当def function时,一个function对象会实现__get__方法,so,一个function就是一个descriptor,根据__get__(self, inst, cls)中传入参数的不同,返回不同的输出。

 4、property & super 也基于descriptor

 参考:http://docs.python.org/2.7/reference/datamodel.html?highlight=__mro__#implementing-descriptors

 参考:http://www.cnblogs.com/btchenguang/archive/2012/09/18/2690802.html

posted on 2013-12-01 22:03  Tekkaman  阅读(275)  评论(0编辑  收藏  举报