【问题标题】:Class definition == works but != doesn't类定义 == 有效,但 != 无效
【发布时间】:2019-09-18 01:47:23
【问题描述】:

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

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

【问题讨论】:

  • __ne__ 中,应该是self.__eq__(other) 而不是self.__eq__(self, other) :)
  • 另一方面:你真的需要这个课程吗? tuple 的行为似乎与您实现的方式非常接近。
  • 谢谢大家,愚蠢的错误。这个类是一个假人,我只保留了示例的必要部分。

标签: python class equality


【解决方案1】:

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

return not self.__eq__(self, other)

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

return not self.__eq__(other)

【讨论】:

    【解决方案2】:
    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)
    

    【讨论】:

    • 愚蠢的错误...谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 2018-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多