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

这一生的挚爱 提交于 2019-11-29 04:17:55

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 <unbound method ...>, whereas if im_self member is not None, the repr is <bound method...>

Python 3 is different. Unbound methods have a repr <function x.f at 0x7fd419cf69e0> 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!