Python __eq__() Method
The __eq__() Method
Most data types (string, number, list, etc) compare by content when you use == to compare them.
For objects, this is not the case. The == operator checks if the two variables point to the exact same object in memory - not if their content matches.
The __eq__() method allows you to change this behavior.
Example
Without __eq__(), two objects with identical values are still not considered equal:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Linus", 30)
p2 = Person("Linus", 30)
print(p1 == p2)
Try it Yourself »
Change how to Compare
Add __eq__() to define what "equal" means for your class:
Example
Add a __eq__() method that defines that two objects are equal if the values are equal:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return self.name == other.name and self.age == other.age
p1 = Person("Linus", 30)
p2 = Person("Linus", 30)
print(p1 == p2)
Try it Yourself »
Note: Did you notice the parameter other? It represents the other object being compared to.