首页 > 编程 > Python > 正文

Python描述器descriptor详解

2020-02-23 06:21:29
字体:
来源:转载
供稿:网友

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表