该
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 == otherclass B(object): def __eq__(self, other): print("B __eq__ called: %r == %r ?" % (self, other)) return self.value == othera = A()a.value = 3b = B()b.value = 4a == b它会打印:
A __eq__ called: <__main__.A object at 0x013BA070> == <__main__.B object at 0x013BA090> ?B __eq__ called: <__main__.B object at 0x013BA090> == 3 ?



