有人能解释一下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__
没有给我原始的输出
方法对象。我理解得对吗?在
文本描述绑定行为;如果一个方法已经被绑定,但是您通过descriptor protocol检索它,那么方法对象的行为将与函数对象一样,但是
__func__
属性将被重用,而不是让新方法对象指向旧的方法对象。在通过将
foo
作为类或实例的属性访问,可以触发描述符协议:在上面的会话中,我使用
A.__dict__
绕过描述符协议。您可以看到A.__dict__['foo']
是一个函数对象,但是A.__dict__['bar']
是一个未绑定的方法。然而,当您访问A.bar
或a.bar
时,会得到一个指向原始函数对象的方法对象,而不是指向我们从A.foo
检索到的方法。在因此您的理解似乎是正确的;}将导致与
b.f
是(绑定)a.foo
方法,因此{a.foo.__func__
相同的对象。在相关问题 更多 >
编程相关推荐