python - python中的平等和继承

标签 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__ 的正确方法是什么?

最佳答案

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

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

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

关于python - python中的平等和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45216181/

相关文章:

python - 在接近给定数字的python数组中查找多个值

C++使用派生类的对象访问基类的 protected 成员函数

python - Django多表继承,如何知道哪个是模型的子类?

javascript - 变量属性的继承

C如何比较未知类型的2个元素

c# - 在非不可变类型中覆盖 == 运算符

python - 动态类变量 - locals() 与 __metaclass__

python - 在 Ubuntu 中重新启动崩溃的 Python 脚本?

.NET object.Equals(object, object) 的 Java 等价物

python - 如何选择二维数组中的特定行和列