You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 22:55:07