由于Python不提供比较运算符的左/右版本,它如何决定调用哪个函数?__eq__如何在Python中以什么顺序处理?
class A(object):
def __eq__(self, other):
print "A __eq__ called"
return self.value == other
class B(object):
def __eq__(self, other):
print "B __eq__ called"
return self.value == other
>>> a = A()
>>> a.value = 3
>>> b = B()
>>> b.value = 4
>>> a == b
"A __eq__ called"
"B __eq__ called"
False
这似乎同时调用__eq__
函数。只是寻找官方的决策树。
绝对正确。总而言之,这些测试应该是“return self.value == other.value”。 – 2010-08-28 00:17:26
谢谢Ned!只是一些人:这取决于你在找什么。例如,假设我想:a == 3和a == b都为真(将b.value更改为3)。 – PyProg 2010-08-28 00:48:08