【发布时间】:2016-08-23 14:59:14
【问题描述】:
最近我阅读了“Fluent python”并了解了== 运算符如何使用__eq__() 方法处理python 对象。但它如何与 python2 中的int 实例一起工作?
>>> a = 1
>>> b = 1
>>> a == b
True
>>> a.__eq__(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__eq__'
在python3中所有a.__eq__(b)返回True
【问题讨论】:
-
stackoverflow.com/questions/3588776/… 看看这里的几个答案,我认为他们解释得很好
-
大胆猜测,但
from operator import eq; eq(2,2)在 Python2 中确实有效。或者使用__cmp__ -
a.__cmp__存在,这可能是 Python 2 正在使用的。
标签: python python-2.7 python-internals