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

  • A+
Category:Languages

I tried to implement some wildcard class that compares equal to any string, but false to anything else. However, the != operator does not appear to call my __neq__ member as expected:

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 

What am I doing wrong?


For overriding the != you need to define __ne__ but you defined __neq__.

So you have to change

def __neq__(self, o): 

to

def __ne__(self, o): 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: