用户定义的方法

2024-05-13 03:13:12 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能解释一下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__没有给我原始的输出 方法对象。我理解得对吗?在


Tags: theinstance用户outputobjectfooisfunction
1条回答
网友
1楼 · 发布于 2024-05-13 03:13:12

文本描述绑定行为;如果一个方法已经被绑定,但是您通过descriptor protocol检索它,那么方法对象的行为将与函数对象一样,但是__func__属性将被重用,而不是让新方法对象指向旧的方法对象。在

通过将foo作为类或实例的属性访问,可以触发描述符协议:

>>> 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>

在上面的会话中,我使用A.__dict__绕过描述符协议。您可以看到A.__dict__['foo']是一个函数对象,但是A.__dict__['bar']是一个未绑定的方法。然而,当您访问A.bara.bar时,会得到一个指向原始函数对象的方法对象,而不是指向我们从A.foo检索到的方法。在

因此您的理解似乎是正确的;b.f是(绑定)a.foo方法,因此{}将导致与a.foo.__func__相同的对象。在

相关问题 更多 >