Python NOT EQUAL Operator with Custom Object

We can also use the NOT EQUAL operator with custom objects in Python. Here is an example of how the does not equal Python operator works with custom objects.

The Python __ne__() decorator gets called whenever the does not equal Python operator in Python is used. We can override this function to alter the nature of the ‘not equal’ operator.

Python3




class Student:
 
    def __init__(self, name):
        self.student_name = name
 
    def __ne__(self, x):
        # return true for different types
        # of object
        if type(x) != type(self):
            return True
           
        # return True for different values
        if self.student_name != x.student_name:
            return True
        else:
            return False
 
s1 = Student("Shyam")
s2 = Student("Raju")
s3 = Student("babu rao")
 
print(s1 != s2)
print(s2 != s3)


Output:

True
True


Python NOT EQUAL operator

In this article, we are going to see != (Not equal) operators. In Python,  != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal. 

Similar Reads

Python NOT EQUAL operators Syntax

The Operator not equal in the Python description:...

Examples of NOT EQUAL Operator in Python

Here are a few examples of Python NOT EQUAL operators....

Python NOT EQUAL Operator with Custom Object

...