类定义==有效,但!=无效

Mat*_*ieu 1 python equality class

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

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)
Run Code Online (Sandbox Code Playgroud)

如果我尝试的话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
Run Code Online (Sandbox Code Playgroud)

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

Dee*_*ace 5

def __ne__(self, other):
    """ != comparison method."""
    return not self.__eq__(self, other)
Run Code Online (Sandbox Code Playgroud)

你不应该明确地传递selfself.__eq__就像你不及格selfself._key()

def __ne__(self, other):
    """ != comparison method."""
    return not self.__eq__(other)
Run Code Online (Sandbox Code Playgroud)