我有一个错误,在使用 is
时我依赖于彼此相等的方法。事实证明并非如此:
>>> class What:
... def meth(self):
... pass
>>> What.meth is What.meth
True
>>> inst = What()
>>> inst.meth is inst.meth
False
为什么会这样?它适用于常规功能:
>>> def func(): pass
>>> func is func
True
最佳答案
每次访问方法对象时,都会创建。函数充当 descriptors ,当他们的 .__get__
方法被调用时返回一个方法对象:
>>> What.__dict__['meth']
<function What.meth at 0x10a6f9c80>
>>> What.__dict__['meth'].__get__(What(), What)
<bound method What.meth of <__main__.What object at 0x10a6f7b10>>
如果您使用的是 Python 3.8 或更高版本,则可以改用 ==
相等性测试。在 Python 3.8 及更高版本上,如果两个方法的 .__self__
和 .__func__
属性是相同的对象(因此,如果它们包装相同的函数,并绑定(bind)到相同的例如,都使用 is
进行了测试。
在 3.8 之前,方法 ==
行为根据方法的实现方式不一致 - Python 方法和两种 C 方法类型之一比较 __self__
是否相等身份,而另一种 C 方法类型通过身份比较 __self__
。参见 Python issue 1617161 .
如果您需要测试这些方法是否表示相同的底层函数,请测试它们的__func__
属性:
>>> What.meth == What.meth # functions (or unbound methods in Python 2)
True
>>> What().meth == What.meth # bound method and function
False
>>> What().meth == What().meth # bound methods with *different* instances
False
>>> What().meth.__func__ == What().meth.__func__ # functions
True
关于python - 为什么方法没有引用相等性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15977808/