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
#with integers
print(int(1).__ne__(1)) #Same as print(1 != 1)
#with floats
print(float(2.5).__ne__(2.55))# Same as print(2.5 != 2.55)
Example with lists
L = [1, 2, 3]
L2 = [3, 4, 5]
#Check that L is not equal to L2
print(L.__ne__(L2)) #Same as print(L != L1)
L3 = sorted([2, 3, 1])
#Check that L is not equal to l3
print(L.__ne__(L3)) # Same as print(L != l3)
Example with dictionaries.
D = {1: "One", 2: "Two", 3: "Three"}
D2 = {"One": 1, "Two": 2, "Three": 3}
print(D.__ne__(D2))
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:
#an integer and a float
print(int(1).__ne__(1.0))
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:
class Country:
def __init__(self, name):
self.name = name
c = Country("India")
c2 = Country("India")
print(c != c2)
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.
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.
class Country:
def __init__(self, name):
self.name = name.capitalize()
def __ne__(self, other):
if isinstance(other, Country): #Ensure that other is an instance of this class.
return other.name != self.name
return True
#create instances
c = Country("India")
c2 = Country("India")
c3 = Country("Japan")
#Use the inequality operator on the instances
print(c != c2)
print(c != c3)
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:
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def __ne__(self, other):
if isinstance(other, Point):
return (other.x, other.y) != (self.x, self.y)
return True
p1 = Point(1, 2)
p2 = Point(3, 7)
p3 = Point(1, 2)
print(p1 != p2)
print(p1 != p3)
print(p2 != p3)
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:
class Book:
def __init__(self, title, author, isbn):
self.title = title
self.author = author
self.isbn = isbn
def __ne__(self, other):
if isinstance(other, Book):
return other.isbn != self.isbn
return True
book1 = Book("The Cat in the Hat", "Dr. Seuss", "123456")
book2 = Book("The Cat in the Hat", "Dr. Seuss", "123456")
book3 = Book("Book Thief", "Markus Zusak", "987654")
print(book1 != book2)
print(book2 != book3)