为什么!=运算符不会调用我的'__neq__'方法?

use*_*337 0 python methods comparison-operators

我试图实现一些比较等于任何字符串的通配符类,但是对其他任何字符串都是false.但是,!=运营商似乎没有__neq__按预期呼叫我的会员:

class A(str):
    def __cmp__(self, o):
        return 0 if isinstance(o, str) else -1

    def __eq__(self, o):
        return self.__cmp__(o) == 0

    def __neq__(self, o):
        return self.__cmp__(o) != 0

a = A()
b = 'a'
print(a == b) # Prints True, as expected
print(a != b) # Prints True, should print False
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Cho*_*opi 13

为了覆盖!=你需要定义,__ne__但你定义__neq__.

所以你必须改变

def __neq__(self, o):
Run Code Online (Sandbox Code Playgroud)

def __ne__(self, o):
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!这是一个愚蠢的错误,但我永远不会抓住它! (2认同)