由于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
Run Code Online (Sandbox Code Playgroud)
这似乎称为两种__eq__功能.只是寻找官方的决策树.
Python文档清楚地说明了x==y调用x.__eq__(y).然而,似乎在许多情况下,情况正好相反.它记录了何时或为何发生这种情况,以及如何确定我的对象__cmp__或__eq__方法是否会被调用.
编辑:只是为了澄清,我知道这__eq__是在优先考虑__cmp__,但我不清楚为什么y.__eq__(x)被优先调用x.__eq__(y),当后者是文档状态将发生.
>>> class TestCmp(object):
... def __cmp__(self, other):
... print "__cmp__ got called"
... return 0
...
>>> class TestEq(object):
... def __eq__(self, other):
... print "__eq__ got called"
... return True
...
>>> tc = TestCmp()
>>> te = TestEq()
>>>
>>> 1 == tc
__cmp__ got called
True
>>> tc == 1
__cmp__ got called
True
>>>
>>> 1 == te …Run Code Online (Sandbox Code Playgroud)