__eq__如何在Python中以什么顺序处理? [英] How is __eq__ handled in Python and in what order?
问题描述
由于Python不提供其比较运算符的左/右版本,因此它如何决定调用哪个函数?
Since Python does not provide left/right versions of its comparison operators, how does it decide which function to call?
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__
函数.只是在寻找官方决策树.
This seems to call both __eq__
functions. Just looking for the official decision tree.
推荐答案
a == b
表达式调用A.__eq__
,因为它存在.其代码包括self.value == other
.由于int不知道如何将自己与B进行比较,因此Python尝试调用B.__eq__
来查看其是否知道如何将自己与int进行比较.
The a == b
expression invokes A.__eq__
, since it exists. Its code includes self.value == other
. Since int's don't know how to compare themselves to B's, Python tries invoking B.__eq__
to see if it knows how to compare itself to an int.
如果您修改代码以显示正在比较的值:
If you amend your code to show what values are being compared:
class A(object):
def __eq__(self, other):
print("A __eq__ called: %r == %r ?" % (self, other))
return self.value == other
class B(object):
def __eq__(self, other):
print("B __eq__ called: %r == %r ?" % (self, other))
return self.value == other
a = A()
a.value = 3
b = B()
b.value = 4
a == b
它将打印:
A __eq__ called: <__main__.A object at 0x013BA070> == <__main__.B object at 0x013BA090> ?
B __eq__ called: <__main__.B object at 0x013BA090> == 3 ?
这篇关于__eq__如何在Python中以什么顺序处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!