如何在函数中使用预定义的描述符? [英] How work pre-defined descriptors in functions?
问题描述
-
def a():
return'x'
a .__ get __.__ doc__
'descr .__ get __(obj [类型]) - >值'
什么是obj和什么类型?
-
>>> a .__ get __()
TypeError:预计至少有1个参数,得到0
>>> a .__ get __('s')
< bound method?.a of's'>
>>> a .__ get __('s')()
TypeError:a()不带任何参数(给出1)
当然,我不能用不带任何参数的函数来实现这个技巧。是否仅仅需要用参数调用函数?
-
>>> 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:
def a(): return 'x' a.__get__.__doc__ 'descr.__get__(obj[, type]) -> value'
What is the obj and what is the type?
>>> 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?
>>> 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屋!