The __ne__()
method checks for inequality between two objects of the same class i.e it asserts that the two objects are not equal. It is the method that gets called when we use the inequality operator(
!=
) with objects. So if you have ever used the inequality operator, you have also indirectly used the __ne__()
method.
The method is practically the opposite of the __eq__()
method which checks for equality instead of inequality.
All Python objects have this method defined by default, this makes it possible to use the inequality operator consistently with any object. The following examples demonstrates how the method works with some builtin objects.
Example with numerical Values
Example with lists
Example with dictionaries.
In the cases when the two objects being compared do not belong to the same class/ type, the method may return False
and in other cases, raise a NotImplemented
exception. For example:
The __ne__() method with custom objects
By default, the __ne__()method(and accordingly, the !=
operator) will treat two objects belonging to the same class as not equal unless we override the method in the class definition. For example:
We can define the __ne__() method in order to provide a more specific and logical criteria for comparison. For example in the above example, it would be more logical to consider two countries with the same name as equal. In order to define the method in our classes we use the following syntax:
def __ne__(self, other): #statements.
copy
self |
This is a required parameters for all instance methods. It references the current instance. |
other |
The other object to to be compared with the current instance. The object should be from the same class unless we want it to be from another compatible class. |
The method should return a boolean value; True
if the objects are not equal and False
otherwise.
The following example shows the previous example with the __ne__() method defined.
Note: It is important to ensure that the two objects actually belong to the same class. This ensures that the __ne__() function works correctly and returns the correct result even when the two classes contains attributes with a similar name.
The builtin isisnstance()
function can be used to tell whether an object is an instance of a given class or not.
A more practical example:
In the above case, the Point objects will be regarded as not equal if both x and y are not equal for both points.
And a final example: