如何在函数中使用预定义的描述符? [英] How work pre-defined descriptors in functions?

查看:151
本文介绍了如何在函数中使用预定义的描述符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python函数有一个描述符。我相信在大多数情况下,我不应该直接使用它,但我想知道这个功能是如何工作的?我尝试了一些操作这样的对象:


  1.  

      def a():
    return'x'

    a .__ get __.__ doc__
    'descr .__ get __(obj [类型]) - >值'

    什么是obj和什么类型?


  2.  

     >>> a .__ get __()
    TypeError:预计至少有1个参数,得到0

    >>> a .__ get __('s')
    < bound method?.a of's'>

    >>> a .__ get __('s')()
    TypeError:a()不带任何参数(给出1)

    当然,我不能用不带任何参数的函数来实现这个技巧。是否仅仅需要用参数调用函数?


  3.  

     >>> def d(arg1,arg2,arg3):
    返回arg1,arg2,arg3
    >>> d .__ get __('s')('x','a')
    ('s','x','a')

    为什么直接由 __获取__ 以及其他所有返回对象所引发的第一个参数?



解决方案

a .__ get __ 将一个函数绑定到一个对象。因此:

  class C(object):
pass

def a(s) :
return 12

a = a .__ get __(C)



  class C(object):
def a(self):
返回12

(虽然这样做并不是一个好主意,但一方面, C 不会知道它有一个名为 a 的绑定方法,您可以通过执行 dir(C)。基本上, __ get __ 只是绑定过程的一部分)。



这就是为什么你不能为一个不带参数的函数做这件事 - 它必须采用通过特定实例的第一个参数(传统上是 self )。

Python functions have a descriptors. I believe that in most cases I shouldn't use this directly but I want to know how works this feature? I tried a couple of manipulations with such an objects:

  1.  

    def a():
        return 'x' 
    
    a.__get__.__doc__
    'descr.__get__(obj[, type]) -> value'
    

    What is the obj and what is the type?

  2.  

    >>> a.__get__()
    TypeError:  expected at least 1 arguments, got 0
    
    >>> a.__get__('s')
    <bound method ?.a of 's'>
    
    >>> a.__get__('s')()
    TypeError: a() takes no arguments (1 given)
    

    Sure that I can't do this trick with functions which take no arguments. Is it required just only to call functions with arguments?

  3.  

    >>> def d(arg1, arg2, arg3):
            return arg1, arg2, arg3
    >>> d.__get__('s')('x', 'a')
    ('s', 'x', 'a')
    

    Why the first argument taken directly by __get__, and everything else by returned object?

解决方案

a.__get__ is a way to bind a function to an object. Thus:

class C(object):
    pass

def a(s):
    return 12

a = a.__get__(C)

is the rough equivalent of

class C(object):
    def a(self):
        return 12

(Though it's not a good idea to do it this way. For one thing, C won't know that it has a bound method called a, which you can confirm by doing dir(C). Basically, the __get__ does just one part of the process of binding).

That's why you can't do this for a function that takes no arguments- it must take that first argument (traditionally self) that passes the specific instance.

这篇关于如何在函数中使用预定义的描述符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆