Python __func__

Python func

__func__ 是 method 的一个属性,返回的是一个函数对象

验证

class Foo:

    def bar(self):
        ...


a = Foo()
b = Foo()

Foo: ClassObject
a: instance
b: instance

根据 Python 3.0 新特性
Unbound methods are gone for good. ClassObject.method returns an ordinary function object, instance.method still returns a bound method object. The API of bound methods is cleaned up, too. The im_class attribute is removed and im_func + im_self are renamed to func and self. The factory PyMethod_New takes only func and instance as argument.

ClassObject.method 返回一个 function object
instance.method 返回一个 bound method object

因此:
Foo.bar: function object
a.bar: method object

示例:

print(Foo, Foo.bar)

print(a, a.bar, a.bar.__func__)
print(b, b.bar, b.bar.__func__)

输出结果:

<class '__main__.Foo'> <function Foo.bar at 0x7f8692704af0>
<__main__.Foo object at 0x7f8690f858b0> <bound method Foo.bar of <__main__.Foo object at 0x7f8690f858b0>> <function Foo.bar at 0x7f8692704af0>
<__main__.Foo object at 0x7f869252ee20> <bound method Foo.bar of <__main__.Foo object at 0x7f869252ee20>> <function Foo.bar at 0x7f8692704af0>

结论:
虽然 a.bar, b.bar 指向了两个不同的 method object, 但是 a.bar.__func__, b.bar.__func__ 仍然指向的是同一个 function object, 和 Foo.bar 指向的 function object 相同

posted on 2021-06-03 10:37  doubtful  阅读(1056)  评论(0编辑  收藏  举报

导航