python - 为什么int.__eq__在python2中似乎没有实现

标签 python python-2.7 comparison-operators magic-methods

我很头疼,看来我不是唯一的人,但是真的没有解决办法吗?我觉得很难相信!

所以问题是为什么我不能打电话int.__eq__与 2 个运算符(operator)或 i.__eq__与一个?我该如何使用__eq__ (以及其他比较运算符)用于整数序列的每个项目比较?

这是 python2.7.17 的转储:

>>> i = 0
>>> type(i)
<type 'int'>
>>> i.__eq__(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__eq__'
>>> type(i).__eq__(i, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected 1 arguments, got 2
>>> type(i).__eq__(0)
NotImplemented

但是我的 python3.6.9 的 dumo 表现良好:

>>> i = 0
>>> type(i)
<class 'int'>
>>> i.__eq__(0)
True
>>> type(i).__eq__(i, 0)
True
>>> type(i).__eq__(0)  # this is not expected to work, but just for the sake of voodoo.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected 1 arguments, got 0

我知道 python2 不再受支持,但有一些应用程序仅使用 python2,我想让我的代码向后兼容。

那么有人有一个解决方案可以将比较魔术运算符方法破解为 python2 中的函数调用吗?我确信一定有一些解决办法。

似乎有一些这方面的信息。我刚刚读到 python2 在某些情况下会回退到使用 cmp,而在 python3 中没有 cmp (或者我是这样读到的)。所以我想要做的事情不是使用 eq 和 ne 而是使用 cmp 但我喜欢对此的一些额外观点

最佳答案

一般规则是:不要碰 dunderscore 方法,而是使用函数和运算符,这些将根据需要委托(delegate)给 dunderscore 实现。。在您的情况下,您正在寻找 == operator 或功能等效的 operator.eq

from operator import eq
from functools import partial

print eq(1, 2)

f = partial(eq, 1)
print f(2)

关于python - 为什么int.__eq__在python2中似乎没有实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62214848/

相关文章:

python - Python 中是否有某种虚拟数据库?

python - 如何在 python 中使用星期几和月份日期来获取年份?

python - 如何在pyqtgraph中绘制十字准线和绘制鼠标位置?

google-app-engine - 设置 GAE 前端实例类的经验法则

python - 小于或大于 Python 中作为变量的比较

JavaScript if() 语句未按预期评估

Java - 正负零的比较

python - 同一页面中的多个表单,提交时保持数据填充

python - 抑制 Pandas 的科学记数法?

python-2.7 - 如何测试行为中未捕获/未处理的异常?