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