在 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 中,如果您提供 __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/