Class 定义 == 有效但 != 无效

Class definition == works but != doesn't

让我们考虑以下最小示例:

class Dummy:
    def __init__(self, v1, v2, v3):
        self.v1 = v1
        self.v2 = v2
        self.v3 = v3

    def __key(self):
        return (self.v1, self.v2, self.v3)

    def __hash__(self):
        return hash(self.__key())

    def __eq__(self, other):
        """ == comparison method."""
        return isinstance(self, type(other)) and self.__key() == other.__key()

    def __ne__(self, other):
        """ != comparison method."""
        return not self.__eq__(self, other)

D1 = Dummy(1, 2, 3)
D2 = Dummy(1, 4, 5)

如果我尝试 D1 == D2,我会得到 False。但是,如果我尝试 D1 != D2,我会得到:

D1 != D2
Traceback (most recent call last):

  File "<ipython-input-3-82e7c8b040e3>", line 1, in <module>
    D1 != D2

  File "<ipython-input-1-34c16f7f1c83>", line 19, in __ne__
    return not self.__eq__(self, other)

TypeError: __eq__() takes 2 positional arguments but 3 were given

我一直将__ne__()定义为not self.__eq__()。直到现在我都没有遇到任何问题,而且我不明白为什么它不起作用...

def __ne__(self, other):
    """ != comparison method."""
    return not self.__eq__(self, other)

你不应该明确地将 self 传递给 self.__eq__,就像你不将 self 传递给 self._key() 一样:

def __ne__(self, other):
    """ != comparison method."""
    return not self.__eq__(other)

当您从 __ne__ 调用它时,您向 __eq__ 提供了太多参数:

return not self.__eq__(self, other)

应该少一个,因为self是隐式传递的:

return not self.__eq__(other)