为什么方法没有引用相等?

Cla*_*diu 14 python methods identity equality reference

我有一个错误,我在使用时依赖于彼此相等的方法is.事实证明并非如此:

>>> class What(object):
    def meth(self):
        pass

>>> What.meth is What.meth
False
>>> inst = What()
>>> inst.meth is inst.meth
False
Run Code Online (Sandbox Code Playgroud)

为什么会这样?它适用于常规功能:

>>> def func():
    pass

>>> func is func
True
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 21

每次访问时都会创建方法对象.函数充当描述符,在.__get__调用方法时返回方法对象:

>>> What.__dict__['meth']
<function meth at 0x10a6f9c80>
>>> What.__dict__['meth'].__get__(None, What)
<unbound method What.meth>
>>> What.__dict__['meth'].__get__(What(), What)
<bound method What.meth of <__main__.What object at 0x10a6f7b10>>
Run Code Online (Sandbox Code Playgroud)

请改用==相等测试.

如果它们.im_self.im_func属性相同,则两种方法相同.如果您需要测试方法代表相同的底层函数,请测试它们的im_func属性:

>>> What.meth == What.meth     # unbound methods (or functions in Python 3)
True
>>> What().meth == What.meth   # unbound method and bound method
False
>>> What().meth == What().meth # bound methods with *different* instances
False
>>> What().meth.im_func == What().meth.im_func  # functions
True
Run Code Online (Sandbox Code Playgroud)

  • 你有可能修改这个答案吗?在方法相等比较中如何考虑`im_self`的描述目前是错误的. (2认同)