0
0
PythonHow-ToBeginner · 3 min read

How to Implement __eq__ Method in Python for Object Comparison

In Python, implement the __eq__ method inside your class to define how two objects are compared for equality. This method should return True if the objects are considered equal and False otherwise.
📐

Syntax

The __eq__ method is a special method used to compare two objects for equality. It takes two parameters: self (the current object) and other (the object to compare with). It should return True if the objects are equal, otherwise False.

python
def __eq__(self, other):
    if not isinstance(other, YourClassName):
        return False
    return self.attribute == other.attribute
💻

Example

This example shows a Person class where two objects are equal if their name and age are the same.

python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __eq__(self, other):
        if not isinstance(other, Person):
            return False
        return self.name == other.name and self.age == other.age

# Create two person objects
person1 = Person("Alice", 30)
person2 = Person("Alice", 30)
person3 = Person("Bob", 25)

print(person1 == person2)  # True
print(person1 == person3)  # False
Output
True False
⚠️

Common Pitfalls

  • Not checking the type of other can cause errors or wrong comparisons.
  • Forgetting to compare all relevant attributes may lead to incorrect equality results.
  • Not returning False when other is not the same type can cause unexpected behavior.
python
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    # Wrong: no type check and only compares x
    def __eq__(self, other):
        return self.x == other.x

    # Correct:
    # def __eq__(self, other):
    #     if not isinstance(other, Point):
    #         return False
    #     return self.x == other.x and self.y == other.y
📊

Quick Reference

Remember these tips when implementing __eq__:

  • Always check if other is the same class using isinstance().
  • Compare all attributes that define equality.
  • Return False if other is not the expected type.
  • Keep the method simple and clear.

Key Takeaways

Implement __eq__ to define how two objects are compared for equality.
Always check the type of the other object with isinstance before comparing.
Compare all attributes that matter for equality to avoid wrong results.
Return False if the other object is not the same type.
Keep the __eq__ method clear and simple for maintainability.