Python描述器descriptor详解


Posted in Python onFebruary 03, 2015

前面说了descriptor,这个东西其实和Java的setter,getter有点像。但这个descriptor和上文中我们开始提到的函数方法这些东西有什么关系呢?

所有的函数都可以是descriptor,因为它有__get__方法。

>>> def hello():  

    pass  

>>> dir(hello)  

['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '<span style="color: #ff0000;">__get__</span>  

', '__getattribute__',   

'__hash__', '__init__', '__module__', '__name__', '__new__',   

'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure',   

'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']  

>>>  

 注意,函数对象没有__set__和__del__方法,所以它是个non-data descriptor.

方法其实也是函数,如下:

>>> class T(object):  

    def hello(self):  

        pass  

>>> T.__dict__['hello']  

<function hello at 0x00CD7EB0>  

>>> 

 或者,我们可以把方法看成特殊的函数,只是它们存在于类 中,获取函数属性时,返回的不是函数本身(比如上面的<function hello at 0x00CD7EB0>),而是返回函数的__get__方法的返回值,接着上面类T的定义:

>>> T.hello   获取T的hello属性,根据查找策略,从T的__dict__中找到了,找到的是<function hello at 0x00CD7EB0>,但不会直接返回<function hello at 0x00CD7EB0>,因为它有__get__方法,所以返回的是调用它的__get__(None, T)的结果:一个unbound方法。

<unbound method T.hello>
>>> f = T.__dict__['hello']   #直接从T的__dict__中获取hello,不会执行查找策略,直接返回了<function hello at 0x00CD7EB0>

>>> f

<function hello at 0x00CD7EB0>

>>> t = T()                 

>>> t.hello                     #从实例获取属性,返回的是调用<function hello at 0x00CD7EB0>的__get__(t, T)的结果:一个bound方法。
<bound method T.hello of <__main__.T object at 0x00CDAD10>>

>>>

 为了证实我们上面的说法,在继续下面的代码(f还是上面的<function hello at 0x00CD7EB0>):

>>> f.__get__(None, T)  

<unbound method T.hello>  

>>> f.__get__(t, T)  

<bound method T.hello of <__main__.T object at 0x00CDAD10>> 

 好极了!

总结一下:

      1.所有的函数都有__get__方法

      2.当函数位于类的__dict__中时,这个函数可以认为是个方法,通过类或实例获取该函数时,返回的不是函数本身,而是它的__get__方法返回值。

我承认我可能误导你认为方法就是函数,是特殊的函数。其实方法和函数还是有区别的,准确的说:方法就是方法,函数就是函数。

>>> type(f)  

<type 'function'>  

>>> type(t.hello)  

<type 'instancemethod'>  

>>> type(T.hello)  

<type 'instancemethod'>  

>>>  

 函数是function类型的,method是instancemethod(这是普通的实例方法,后面会提到classmethod和staticmethod)。

关于unbound method和bound method,再多说两句。在c实现中,它们是同一个对象(它们都是instancemethod类型的),我们先看看它们里面到底是什么

>>> dir(t.hello)  

['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__', '__getattribute__',   

'__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',   

'__str__', 'im_class', 'im_func', 'im_self'] 

 __call__说明它们是个可调用对象,而且我们还可以猜测,这个__call__的实现应该大致是:转调另外一个函数(我们期望的哪个,比如上面的hello),并以对象作为第一参数。

要 注意的是im_class,im_func,im_self。这几个东西我们并不陌生,在t.hello里,它们分别代表T,hello(这里是存储在 T.__dict__里的函数hello)和t。有了这些我们可以大致想象如何纯Python实现一个instancemethod了:)。

其实还有几个内建函数都和descriptor有关,下面简单说说。

classmethod

classmethod能将一个函数转换成类方法,类方法的第一个隐含参数是类本身 (普通方法的第一个隐含参数是实例本身),类方法即可从类调用,也可以从实例调用(普通方法只能从实例调用)。

>>> class T(object):  

    def hello(cls):  

        print 'hello', cls  

    hello = classmethod(hello)   #两个作用:把hello装换成类方法,同时隐藏作为普通方法的hello   

>>> t = T()  

>>> t.hello()  

hello <class '__main__.T'>  

>>> T.hello()  

hello <class '__main__.T'>  

>>>  

 注意:classmethod是个类,不是函数。classmethod类有__get__方法,所以,上面的t.hello和T.hello获得实际上是classmethod的__get__方法返回值

>>> t.hello  

<bound method type.hello of <class '__main__.T'>>  

>>> type(t.hello)  

<type 'instancemethod'>  

>>> T.hello  

<bound method type.hello of <class '__main__.T'>>  

>>> type(T.hello)  

<type 'instancemethod'>  

>>>  

 从 上面可以看出,t.hello和T.hello是instancemethod类型的,而且是绑定在T上的。也就是说classmethod的 __get__方法返回了一个instancemethod对象。从前面对instancemethod的分析上,我们应该可以推断:t.hello的 im_self是T,im_class是type(T是type的实例),im_func是函数hello

>>> t.hello.im_self  

<class '__main__.T'>  

>>> t.hello.im_class  

<type 'type'>  

>>> t.hello.im_func  

<function hello at 0x011A40B0>  

>>>  

 完全一致!所以实现一个纯Python的classmethod也不难:)

staticmethod

staticmethod能将一个函数转换成静态方法,静态方法没有隐含的第一个参数。

class T(object):  

    def hello():  

        print 'hello'  

    hello = staticmethod(hello)      

>>> T.hello()   #没有隐含的第一个参数  

hello  

>>> T.hello  

<function hello at 0x011A4270>  

>>> 

 T.hello直接返回了一个函数。猜想staticmethod类的__get__方法应该是直接返回了对象本身。

还有一个property,和上面两个差不多,它是个data descriptor。

Python 相关文章推荐
在Django的session中使用User对象的方法
Jul 23 Python
详解django中自定义标签和过滤器
Jul 03 Python
Python minidom模块用法示例【DOM写入和解析XML】
Mar 25 Python
Django对数据库进行添加与更新的例子
Jul 12 Python
Python计算机视觉里的IOU计算实例
Jan 17 Python
PyCharm无法引用自身项目解决方式
Feb 12 Python
python GUI库图形界面开发之PyQt5控件QTableWidget详细使用方法与属性
Feb 25 Python
python3 正则表达式基础廖雪峰
Mar 25 Python
python实现扫雷小游戏
Apr 24 Python
Python-for循环的内部机制
Jun 12 Python
python3中编码获取网页的实例方法
Nov 16 Python
Pandas对每个分组应用apply函数的实现
Dec 13 Python
理解Python中的With语句
Feb 02 #Python
Linux环境下MySQL-python安装过程分享
Feb 02 #Python
Python中用pycurl监控http响应时间脚本分享
Feb 02 #Python
Python列表(list)常用操作方法小结
Feb 02 #Python
Python Sleep休眠函数使用简单实例
Feb 02 #Python
Python中实现从目录中过滤出指定文件类型的文件
Feb 02 #Python
Python实现二分法算法实例
Feb 02 #Python
You might like
php mssql扩展SQL查询中文字段名解决方法
2012/10/15 PHP
php根据年月获取季度的方法
2014/03/31 PHP
php基于表单密码验证与HTTP验证用法实例
2015/01/06 PHP
PHP调用Linux命令权限不足问题解决方法
2015/02/07 PHP
实例详解PHP中html word 互转的方法
2016/01/28 PHP
Yii遍历行下每列数据的方法
2016/10/17 PHP
PHP单例模式定义与使用实例详解
2017/02/06 PHP
[原创]PHP正则删除html代码中a标签并保留标签内容的方法
2017/05/23 PHP
PHP使用mongoclient简单操作mongodb数据库示例
2019/02/08 PHP
showModalDialog 和 showModelessDialog
2007/01/22 Javascript
jquery BS,dialog控件自适应大小
2009/07/06 Javascript
用js获取电脑信息(是使用与IE浏览器)
2013/01/15 Javascript
浅析hasOwnProperty方法的应用
2013/11/20 Javascript
jQuery制作仿Mac Lion OS滚动条效果
2015/02/10 Javascript
javascript仿京东导航左侧分类导航下拉菜单效果
2020/11/25 Javascript
JS验证 只能输入小数点,数字,负数的实现方法
2016/10/07 Javascript
关于Jquery中的事件绑定总结
2016/10/26 Javascript
jquery easyui validatebox remote的使用详解
2016/11/09 Javascript
vue-cli中打包图片路径错误的解决方法
2017/10/26 Javascript
浅谈vue2 单页面如何设置网页title
2017/11/08 Javascript
vue-cli2.9.3 详细教程
2018/04/23 Javascript
详解a标签添加onclick事件的几种方式
2019/03/29 Javascript
Python利用itchat对微信中好友数据实现简单分析的方法
2017/11/21 Python
在Python中实现shuffle给列表洗牌
2018/11/08 Python
Django之模型层多表操作的实现
2019/01/08 Python
Django高级编程之自定义Field实现多语言
2019/07/02 Python
详解Anaconda 的安装教程
2020/09/23 Python
优质美利奴羊毛袜,不只是徒步旅行:Darn Tough Vermont
2018/11/05 全球购物
西班牙在线光学:Visual-Click
2020/06/22 全球购物
2015年幼儿园毕业感言
2014/02/12 职场文书
2015年监理工作总结范文
2015/04/07 职场文书
死亡诗社观后感
2015/06/05 职场文书
中秋联欢会主持词
2015/07/04 职场文书
汉语拼音教学反思
2016/02/22 职场文书
蔬果开业典礼发言稿应该怎么写?
2019/09/03 职场文书
mysql数据库如何转移到oracle
2022/12/24 MySQL