Python3 : inheriting from list breaks automagically provided __ne__ when __eq__ is defined?

标签 python inheritance python-3.x super

在 Python 3 中,如果您提供 __eq__ 方法,通常还会提供一个合理的 __ne__ 来使用您的 __eq__。但是,我有(在 Python 3 中):

class SomeOtherClassWhichInheritsFromList(list):
    def __init__(self):
        super().__init__()
        self.parval = 44

    def __eq__(self, other):
        print ("IN SomeOtherClassWhichInheritsFromList EQ")
        if isinstance(other, SomeOtherClassWhichInheritsFromList):
            return super().__eq__(other) and self.parval == other.parval
        return NotImplemented

class SomeClass(SomeOtherClassWhichInheritsFromList):
    def __init__(self, val):
        super().__init__()
        self.val = val

    def __eq__(self, other):
        print ("IN SomeClass EQ")
        if isinstance(other, SomeClass):
            return super().__eq__(other) and self.val == other.val
        return NotImplemented

如果我这样做:

sc = SomeClass(99)
sc2 = SomeClass(104)

print (sc != sc2)

我希望看到:

IN SomeClass EQ
IN SomeOtherClassWhichInheritsFromList EQ
True

但我看到的是:

False

表明我的 __eq__ 没有被默认提供的 __ne__ 调用。如果我将 SomeOtherClassWhichInheritsFromList 更改为从对象而不是列表继承,它将按预期工作。

这是因为 list 似乎没有 __mro__ 属性,因此我的 __eq__ 方法中的所有 super() 内容都失败了被触发?

注意:我知道我可以添加自己的 __ne__ 方法来调用我的 __eq__ (我必须这样做,因为我确实想从列表继承),但我在这里寻找的是为什么我必须这样做的解释。

最佳答案

如果你定义了__eq__,你也必须始终定义__ne__。 来自 Python 3.2 的“数据模型”文档: """比较运算符之间没有隐含关系。x==y为真并不意味着x!=y为假。因此,在定义eq()时,还应该定义ne() 以便运算符的行为符合预期。"""

Python 3 Data Model

如果您认为“在 Python 3 中,如果您提供 __eq__ 方法,通常还会提供一个合理的 __ne__ 来使用您的 __eq__."- 是 object__ne__ 方法执行此操作。没有引用您在数据模型文档中声明的行为 - 尽管没有显式父类(super class)(因此从 object 继承)的类的行为如您所描述的那样。

关于Python3 : inheriting from list breaks automagically provided __ne__ when __eq__ is defined?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11436977/

相关文章:

c# - 如何将实现公共(public)接口(interface)的集合添加在一起

python - 从 python 中的两个列表创建 Pandas df

python-3.x - PyTorch 时尚-MNIST (ETL)

python - numpy.ma(屏蔽)数组均值方法具有不一致的返回类型

python - 迭代具有不同可能字符的字符串

C++11 可变参数模板 + 继承

objective-c - 子类不继承其功能

python - 如何在 C 函数中访问 python 变量的数据? (参数类型 : void *)

python - 在Python中插入缺失值

python - 按另一个数据框中的值分组