【发布时间】:2017-01-26 06:28:51
【问题描述】:
不要把苹果和橙子混在一起
问题
我正在使用 __eq__ 运算符和 NotImplemented 值。
我试图了解当obj1.__eq__(obj2) 返回NotImplemented 并且obj2.__eq__(obj1) 也返回NotImplemented 时会发生什么。
根据Why return NotImplemented instead of raising NotImplementedError的回答,以及“LiveJournal”博客中的详细文章How to override comparison operators in Python,运行时应该回退到内置行为(基于 == 和 != 的身份)。
代码示例
但是,尝试下面的示例,我似乎为每对对象多次调用 __eq__。
class Apple(object):
def __init__(self, color):
self.color = color
def __repr__(self):
return "<Apple color='{color}'>".format(color=self.color)
def __eq__(self, other):
if isinstance(other, Apple):
print("{self} == {other} -> OK".format(self=self, other=other))
return self.color == other.color
print("{self} == {other} -> NotImplemented".format(self=self, other=other))
return NotImplemented
class Orange(object):
def __init__(self, usage):
self.usage = usage
def __repr__(self):
return "<Orange usage='{usage}'>".format(usage=self.usage)
def __eq__(self, other):
if isinstance(other, Orange):
print("{self} == {other}".format(self=self, other=other))
return self.usage == other.usage
print("{self} == {other} -> NotImplemented".format(self=self, other=other))
return NotImplemented
>>> apple = Apple("red")
>>> orange = Orange("juice")
>>> apple == orange
<Apple color='red'> == <Orange usage='juice'> -> NotImplemented
<Orange usage='juice'> == <Apple color='red'> -> NotImplemented
<Orange usage='juice'> == <Apple color='red'> -> NotImplemented
<Apple color='red'> == <Orange usage='juice'> -> NotImplemented
False
预期行为
我预计只有:
<Apple color='red'> == <Orange usage='juice'> -> NotImplemented
<Orange usage='juice'> == <Apple color='red'> -> NotImplemented
然后回到身份比较id(apple) == id(orange) -> False。
【问题讨论】:
-
我在 Python 2.7 OS X 上
-
在 Windows 和 CentOS7 上与 Python 2.7 的行为相同。 Windows 上的 Python 3.5 和 repl.it 上的正常行为。
标签: python python-2.7 operators