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

标签 python methods identity equality

我有一个错误,在使用 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/

相关文章:

python 结构匹配

python - 将 Python 作为服务运行时出现“404 Not Found”错误

c# - 根据数组中包含的字符串值调用/调用方法

pointers - Golang中嵌入式类型的内部状态-它如何工作?

sql-server - SQL Server,如何设置建表后自增而不丢失数据?

python - 使用 Python OpenCV 在模糊对象周围找到紧密轮廓

python - 加速 Matplotlib

java - 一种在数组中的两个索引之间交换位置的方法

sql-server - 您如何知道下一个身份栏会是什么?

sql - 如何控制 SQL Server 中新标识列的分配顺序?