pla*_*fer 2 python equality python-3.x
我对==操作符在Python 3中的工作方式感到困惑.从文档中,eq(a, b)相当于a == b.也eq和__eq__是等价的.
请看以下示例:
class Potato:
def __eq__(self, other):
print("In Potato's __eq__")
return True
>> p = Potato()
>> p == "hello"
In Potato's __eq__ # As expected, p.__eq__("hello") is called
True
>> "hello" == p
In Potato's __eq__ # Hmm, I expected this to be false because
True # this should call "hello".__eq__(p)
>> "hello".__eq__(p)
NotImplemented # Not implemented? How does == work for strings then?
Run Code Online (Sandbox Code Playgroud)
AFAIK,文档只讨论==- > __eq__映射,但不要说任何事情发生的事情,其中一个参数不是一个对象(例如1 == p),或者当第一个对象__eq__是NotImplemented,就像我们看到的那样"hello".__eq(p).
我正在寻找用于平等的通用算法...大多数,如果不是所有其他SO答案,请参考Python 2的强制规则,这些规则在Python 3中不再适用.
您将混合operator模块中的函数以及用于实现这些运算符的方法.operator.eq(a, b)相当于a == b或者operator.__eq__(a, b),但没有到a.__eq__(b).
在该方面的__eq__方法,==以及operator.eq工作安排如下:
def eq(a, b):
if type(a) is not type(b) and issubclass(type(b), type(a)):
# Give type(b) priority
a, b = b, a
result = a.__eq__(b)
if result is NotImplemented:
result = b.__eq__(a)
if result is NotImplemented:
result = a is b
return result
Run Code Online (Sandbox Code Playgroud)
需要注意的是,真实代码以__eq__绕过实例dicts和custom __getattribute__/ __getattr__methods 的方式执行方法查找.