python中的平等和继承

Jon*_*ler 3 python inheritance equality

当阅读有关如何__eq__在 python 中实现时,例如在这个 SO 问题中,您会得到类似的建议

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)
Run Code Online (Sandbox Code Playgroud)

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

class B(A):
    def new_method(self):
        return self._a + self._b
Run Code Online (Sandbox Code Playgroud)

然后我得到这个问题

>>> a = A(1, 2)
>>> b = B(1, 2)
>>> a == b
True
Run Code Online (Sandbox Code Playgroud)

但显然,ab并不(完全相同)!

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

Bło*_*tek 6

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

def __eq__(self, other):
    return (self._a, self._b, type(self)) == (other._a, other._b, type(other))
Run Code Online (Sandbox Code Playgroud)

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