python - 用户定义的方法和 __func__ 属性

标签 python python-2.7

有人可以解释一下 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.bara.bar 时,您会得到一个指向原始函数对象的方法对象,而不是我们从 A 检索的方法.foo.

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

关于python - 用户定义的方法和 __func__ 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25806225/

相关文章:

python - 我们可以在 pytest 的 setup_module() 或 setup_class 中打印命令行参数吗?

python - 如何使用 Django REST 框架在 Spyder IDE 中启动新的 Web 应用程序

python - 无法从 HTTP POST 请求恢复项目列表

python - PIP 说它安装了一个包,但实际上并没有

python - Matplotlib 交互拖动重叠点

python - 为什么子进程启动 "extra"应用程序?

python |多处理 |分割数据

python - 使用随机游戏数据进行监督学习

python - 按键值查找列表中字典的索引

Python 2.7.x 压缩文件 : slow unzip from network drive (Windows)