Python描述器descriptor详解_python

前面说了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。

时间: 2024-09-17 09:26:59

Python描述器descriptor详解_python的相关文章

python之import机制详解_python

本文详述了Python的import机制,对于理解Python的运行机制很有帮助! 1.标准import: Python中所有加载到内存的模块都放在 sys.modules .当 import 一个模块时首先会在这个列表中查找是否已经加载了此模块,如果加载了则只是将模块的名字加入到正在调用 import 的模块的 Local 名字空间中.如果没有加载则从 sys.path 目录中按照模块名称查找模块文件,模块可以是py.pyc.pyd,找到后将模块载入内存,并加到 sys.modules 中,并

Python中的装饰器用法详解_python

本文实例讲述了Python中的装饰器用法.分享给大家供大家参考.具体分析如下: 这里还是先由stackoverflow上面的一个问题引起吧,如果使用如下的代码: 复制代码 代码如下: @makebold @makeitalic def say():    return "Hello" 打印出如下的输出: <b><i>Hello<i></b> 你会怎么做?最后给出的答案是: 复制代码 代码如下: def makebold(fn):    

打包发布Python模块的方法详解_python

前言 昨天把自己的VASP文件处理库进行了打包并上传到PyPI,现在可以直接通过pip和easy_install来安装VASPy啦(同时欢迎使用VASP做计算化学的童鞋们加星和参与进来), VASPy的GotHub地址:https://github.com/PytLab/VASPy VASPy的PyPI地址:https://pypi.python.org/pypi/vaspy/ 由于自己的记性真是不咋地,怕时间久了就忘了,于是在这里趁热打铁以自己的VASPy程序为例对python的打包和上传进行

python正则表达式re模块详解_python

快速入门 import re pattern = 'this' text = 'Does this text match the pattern?' match = re.search(pattern, text) s = match.start() e = match.end() print('Found "{0}"\nin "{1}"'.format(match.re.pattern, match.string)) print('from {0} to {1}

Python Deque 模块使用详解_python

创建Deque序列: from collections import deque d = deque() Deque提供了类似list的操作方法: d = deque() d.append('1') d.append('2') d.append('3') len(d) d[0] d[-1] 输出结果: 3 '1' '3' 两端都使用pop: d = deque('12345') len(d) d.popleft() d.pop() d 输出结果: 5 '1' '5' deque(['2', '3

利用Python破解验证码实例详解_python

一.前言 本实验将通过一个简单的例子来讲解破解验证码的原理,将学习和实践以下知识点:       Python基本知识       PIL模块的使用 二.实例详解 安装 pillow(PIL)库: $ sudo apt-get update $ sudo apt-get install python-dev $ sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev \ libfreetype6-dev liblcms2-dev lib

Python冒泡排序注意要点实例详解_python

冒泡排序注意三点: 1. 第一层循环可不用循环所有元素. 2.两层循环变量与第一层的循环变量相关联. 3.第二层循环,最终必须循环集合内所有元素. 示例代码一: 1.第一层循环,只循环n-1个元素. 2.当第一层循环变量为n-1时,第二层循环所有元素. s = [3, 4, 1, 6, 2, 9, 7, 0, 8, 5] # bubble_sort for i in range(0, len(s) - 1): for j in range(i + 1, 0, -1): if s[j] < s[j

python xml解析实例详解_python

python xml解析 first.xml  <info> <person > <id>1</id> <name>fsy</name> <age >24</age> </person> <person> <id>2</id> <name>jianjian</name> <age>24</age> </pers

Python深入06——python的内存管理详解_python

语言的内存管理是语言设计的一个重要方面.它是决定语言性能的重要因素.无论是C语言的手工管理,还是Java的垃圾回收,都成为语言最重要的特征.这里以Python语言为例子,说明一门动态类型的.面向对象的语言的内存管理方式. 对象的内存使用 赋值语句是语言最常见的功能了.但即使是最简单的赋值语句,也可以很有内涵.Python的赋值语句就很值得研究. a = 1 整数1为一个对象.而a是一个引用.利用赋值语句,引用a指向对象1.Python是动态类型的语言(参考动态类型),对象与引用分离.Python