Sometimes, we want to compare object instances for equality by their attributes with Python.
In this article, we’ll look at how to compare object instances for equality by their attributes with Python.
How to compare object instances for equality by their attributes with Python?
To compare object instances for equality by their attributes with Python, we can add the __eq__ method into our class.
For instance, we write
class MyClass:
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
def __eq__(self, other):
if not isinstance(other, MyClass):
return NotImplemented
return self.foo == other.foo and self.bar == other.bar
to create the MyClass class.
In it, we add the foo and bar instance variables.
And we add the __eq__ method to let us check for object equality by checking the value of each attribute.
We use
self.foo == other.foo and self.bar == other.bar
to do the check if self and other are both MyClass instances.
Then we can do the equality check with x == y where x and y are both MyClass instances.
Conclusion
To compare object instances for equality by their attributes with Python, we can add the __eq__ method into our class.