我很头疼,看来我不是唯一的人,但是真的没有解决办法吗?我觉得很难相信!
所以问题是为什么我不能打电话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/