Abstract smoke background

Comparing Points the Pythonic Way

Implementing Equality in a Custom Class Using __eq__ Method


Introduction

In object-oriented programming, defining how objects should be compared is a key part of designing a class. Imagine you’re working with a class called Point that represents a point in 2D space with x and y coordinates. By default, comparing two objects in Python using == checks if they are the same instance, not if they hold the same data. But what if you want to check if two points lie at the same location? That’s where implementing a custom equality method (__eq__) becomes essential.

Master Python: 600+ Real Coding Interview Questions
Master Python: 600+ Real Coding Interview Questions

Let’s say you have a class defined as:

class Point:
def __init__(self, x, y):
self.x = x
self.y = y

Now if you create two points:

p1 = Point(2, 3)
p2 = Point(2, 3)

And try comparing them using:

print(p1 == p2)

Machine Learning & Data Science 600+ Real Interview Questions
Machine Learning & Data Science 600 Real Interview Questions

You’ll get False because they are two different instances. To change this behavior, you need to define the __eq__ method inside your class:

class Point:
def __init__(self, x, y):
self.x = x
self.y = y

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

With this method in place, comparing p1 == p2 will now return True, as both points have the same coordinates. This method checks whether other is an instance of Point and then compares the x and y values.

Additionally, if you plan to use instances of this class in sets or as dictionary keys, you should also implement the __hash__ method:

   def __hash__(self):
return hash((self.x, self.y))

This ensures consistent behavior between equality and hashing.

Master LLM and Gen AI: 600+ Real Interview Questions
Master LLM and Gen AI: 600+ Real Interview Questions

Conclusion

To compare two custom objects like 2D points meaningfully, it’s important to override the __eq__ method in your class. This enables Python to evaluate equality based on internal data rather than memory location. With this simple implementation, your Point class becomes more intuitive and useful for real-world applications like graphics, geometry, and simulations. Defining equality properly not only makes your code cleaner but also aligns it with Python’s principle of clarity and correctness.

























Leave a Reply