python 中的平等与继承

Equality and inheritance in python

阅读有关如何在 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

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

然后我得到这个问题

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

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

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

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

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

这样A(1, 2) == B(1,2)returnsFalse.

当对两种类型的对象进行比较时,一种类型派生自另一种类型,Python 确保在派生的 class 上调用运算符方法(在这种情况下,B).

因此,为了确保 B 对象与 A 对象的比较不同,您可以在 B:

中定义 __eq__
class B(A):
    def __eq__(self, other):
        return isinstance(other, B) and super(B, self).__eq__(other)