有人可以解释一下 Python datamodel reference 中关于用户定义函数的以下部分的内容吗?大约是?
When a user-defined method object is created by retrieving another method object from a class or instance, the behaviour is the same as for a function object, except that the
__func__
attribute of the new instance is not the original method object but its__func__
attribute.
我尝试用以下方法进行测试:
class A(object):
def foo(self):
print 'done'
bar = foo
class B(object): pass
a = A()
b = B()
b.f = a.foo
b.f.__func__ #output:- <function foo at 0x7fe55bed4230>
a.foo.__func__ #output:- <function foo at 0x7fe55bed4230>
这两个语句都给了我相同的输出,但是 b.f.__func__
没有给我原始的输出
方法对象。我理解正确吗?
最佳答案
文本描述了绑定(bind)行为;如果一个方法已经绑定(bind),但您通过 descriptor protocol 检索它那么方法对象的行为就像函数对象一样,但 __func__ 属性被重用,而不是让新方法对象指向旧方法对象。
您可以通过访问 foo
作为类或实例的属性来触发描述符协议(protocol):
>>> class A(object):
... def foo(self):
... print 'done'
...
>>> a = A()
>>> a.foo
<bound method A.foo of <__main__.A object at 0x1007611d0>>
>>> A.foo
<unbound method A.foo>
>>> A.__dict__['foo']
<function foo at 0x10075cc08>
>>> A.bar = A.foo
>>> A.bar
<unbound method A.foo>
>>> A.__dict__['bar']
<unbound method A.foo>
>>> a.bar
<bound method A.foo of <__main__.A object at 0x1007611d0>>
>>> a.bar.__func__
<function foo at 0x10075cc08>
在上面的 session 中,我使用 A.__dict__
绕过描述符协议(protocol)。您可以看到 A.__dict__['foo']
是一个函数对象,但 A.__dict__['bar']
是一个未绑定(bind)的方法。然而,当您访问 A.bar
或 a.bar
时,您会得到一个指向原始函数对象的方法对象,而不是我们从 A 检索的方法.foo
.
所以你的理解似乎是正确的; b.f
是(绑定(bind))a.foo
方法,因此 b.f.__func__
将导致与 a.foo 相同的对象。 __func__
.
关于python - 用户定义的方法和 __func__ 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25806225/