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

时间:2019-04-29 12:22:07

标签: python class equality

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

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__()。直到现在我都没有遇到任何问题,而且我不知道为什么它不起作用...

2 个答案:

答案 0 :(得分:5)

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)

答案 1 :(得分:1)

__eq__调用__ne__时,您提供了太多参数:

return not self.__eq__(self, other)

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

return not self.__eq__(other)
相关问题