Sometimes, we want to support equivalence (“equality”) check in Python classes.
In this article, we’ll look at how to support equivalence (“equality”) check in Python classes.
How to support equivalence (“equality”) check in Python classes?
To support equivalence (“equality”) check in Python classes, we can override the __eq__ method in the Python class.
For instance, we write:
class Number:
def __init__(self, number):
self.number = number
def __eq__(self, other):
if isinstance(other, Number):
return self.number == other.number
return False
n1 = Number(1)
n2 = Number(1)
print(n1 == n2)
to add the __eq__ method which checks for the value of self.number to determine equality of a Number instances instead of using the default way, which is to compare object ID for equality.
We only do the check if other is a Number instance. Otherwise, we return False directly.
Next, we create 2 Number instances with the same value for self.number.
Therefore, n1 and n2 should be equal according to our check, and so True is printed.
Conclusion
To support equivalence (“equality”) check in Python classes, we can override the __eq__ method in the Python class.