该a == b
表达式调用A.__eq__
,因为它存在。其代码包括self.value == other
。由于int不知道如何将自己与B进行比较,因此Python尝试调用B.__eq__
以查看是否知道如何将自己与int进行比较。
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 ?