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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM