python中的平等和继承

时间:2017-07-20 13:26:43

标签: python inheritance equality

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

但显然,ab不是(确切)相同!

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

2 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:2)

在两种类型的对象之间进行比较时,其中一种类型派生自另一种类型,Python确保在派生类上调用operator方法(在本例中为B)。

因此,为了确保B个对象与A个对象的比较不同,您可以在__eq__中定义B

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