Computer >> Computer tutorials >  >> Programming >> Python

How do we use equivalence (“equality”) operator in Python classes?


If we use the equality operator as in the code below, we get false as output

class Integer:
    def __init__(self, number):
        self.number = number

n1 = Integer(1)
n2 = Integer(1)
print bool(n1 == n2)

Output

False

This is because Python by default uses the object identifiers for comparison operations:

To overcome this issue we must override the __eq__function

class Integer:
    def __init__(self, number):
        self.number = number
    def __eq__(self, other):

       if isinstance(self, other.__class__):

          return self.__dict__ == other.__dict__

       return False
n1 = Integer(1)
n2 = Integer(1)
print bool (n1 == n2)
print bool (n1 != n2)

Output

True
True

For Python 2.x, we also have to overide the __ne__function as well. This is not necessary for Python 3.x. As per documentation following holds true.

By default, __ne__() delegates to __eq__() and inverts the result unless it is NotImplemented. There are no other implied relationships among the comparison operators, for example, the truth of (x<y or x==y) does not imply x<=y.