zoukankan      html  css  js  c++  java
  • 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 相同

  • 相关阅读:
    大数据面经
    mysql复习(2)
    java容器
    内存管理
    垃圾收集
    输入/输出流
    排序算法的稳定性及其汇总
    java传值与传引用
    linux复习6
    linux复习5
  • 原文地址:https://www.cnblogs.com/dbf-/p/14844200.html
Copyright © 2011-2022 走看看