Skip to main content
 首页 » 编程设计

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

2025年05月04日14myhome

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

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)