Skip to main content
 首页 » 编程设计

python之python中的平等和继承

2025年05月04日15qq78292959

当阅读有关如何在 python 中实现 __eq__ 时,例如 this SO question , 你会得到像这样的建议

class A(object): 
    def __init__(self, a, b): 
        self._a = a 
        self._b = b 
 
    def __eq__(self, other): 
        return (self._a, self._b) == (other._a, other._b) 

现在,我在将它与继承相结合时遇到了问题。具体来说,如果我定义一个新类

class B(A): 
    def new_method(self): 
        return self._a + self._b 

然后我得到这个问题

>>> a = A(1, 2) 
>>> b = B(1, 2) 
>>> a == b 
True 

但显然,a 和 b 并不(完全)相同!

通过继承实现 __eq__ 的正确方法是什么?

请您参考如下方法:

如果您的意思是不同(子)类的实例不应该相等,请考虑比较它们的类型:

def __eq__(self, other): 
    return (self._a, self._b, type(self)) == (other._a, other._b, type(other)) 

这样 A(1, 2) == B(1,2) 返回 False。