Why does id() of an unbound method in Python 2 change for every access

前端 未结 1 1439
轮回少年
轮回少年 2020-12-16 22:38

Python 2.6.5 (r265:79063, Oct 1 2012, 22:07:21) [GCC 4.4.3]

>>> class myclass:
...     def func(self):
...             pass

>>> dd = myc         


        
1条回答
  •  情深已故
    2020-12-16 23:07

    This is because the methods on a class (old or new) work really like attributes with the descriptor __get__ method; On python 2 the code

    foo = FooClass.bar_method
    

    is analogous to

    import types
    foo = types.MethodType(FooClass.__dict__['bar_method'], None, FooClass)
    

    It will create a new instance of instancemethod(bar_method, None, FooClass) on each access. The original function is available as FooClass.bar_method.im_func and the class instance in foo.im_class. The type for both bound and unbound methods is the same instancemethod; if the im_self member is None, the instancemethod instance has the repr , whereas if im_self member is not None, the repr is

    Python 3 is different. Unbound methods have a repr and the id is always the same, that is they are just general functions. In Python 3 you can pass anything for self of an unbound undecorated method, even None, it is just a function with a dot in its name.

    0 讨论(0)
提交回复
热议问题