Python相等性细节探究:为何a==b与a.__eq__(b)结果不一致?
为什么
a == b和a.__eq__(b)结果不同? 这是因为Python对父子类实例之间的==比较有特殊处理逻辑:
- 执行
a == b时,Python先调用a.__eq__(b),这里返回False(因为type(b)是B而非A); - 由于
a和b属于父子类关系(B继承自A),Python不会直接用False作为最终结果,而是会继续调用b.__eq__(a); b继承了A的__eq__方法,此时type(a)是A,所以b.__eq__(a)返回True;- 最终
a == b的结果取第二次调用的返回值True,因此你的断言失败。
而直接调用a.__eq__(b)只会执行这一个方法,不会触发后续的反向比较,所以结果是False。
你可以通过添加打印语句验证调用流程:
class A: def __eq__(self, other: object) -> bool: print(f"A.__eq__ called: self type={type(self)}, other type={type(other)}") return type(other) is A class B(A): pass if __name__ == '__main__': a = A() b = B() print("a.__eq__(b):", a.__eq__(b)) print("a == b:", a == b)
运行输出:
A.__eq__ called: self type=<class '__main__.A'>, other type=<class '__main__.B'> a.__eq__(b): False A.__eq__ called: self type=<class '__main__.A'>, other type=<class '__main__.B'> A.__eq__ called: self type=<class '__main__.B'>, other type=<class '__main__.A'> a == b: True
内容的提问来源于stack exchange,提问作者Sebastian Thomas
相关产品推荐
相关产品推荐

