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

Why does the != operator not call my '__neq__' method?

我尝试实现一些通配符 class,它比较等于任何字符串,但对其他任何字符串都是假的。但是,!= 运算符似乎没有按预期调用我的 __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

我做错了什么?

要覆盖 !=,您需要定义 __ne__,但您定义了 __neq__

所以你必须改变

def __neq__(self, o):

def __ne__(self, o):