Why does the != operator not call my ‘__neq__’ method? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Why does the != operator not call my ‘__neq__’ method? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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?

Answer

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):
We are here to answer your question about Why does the != operator not call my ‘__neq__’ method? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji