Dunder: Point Equality

Dunder: Point Equality

Write a Point class where == compares coordinates, not object identity.

Point(x, y)
  • __init__(self, x, y) — stores both as attributes.
  • __eq__(self, other) — returns True if self and other have the same x and the same y.

Examples

Point(1, 2) == Point(1, 2)   // → True   (same coordinates, different objects)
Point(1, 2) == Point(3, 4)   // → False

Walkthrough

Thinking it through

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

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

Without __eq__, == on two Point objects would fall back to Python's default behavior: checking whether they're the exact same object in memory — so even Point(1, 2) == Point(1, 2) would be False, since those are two separate objects that just happen to hold equal coordinates. That's rarely what you actually want when comparing two values that represent the same thing.

Defining __eq__(self, other) overrides that default: now point1 == point2 calls Point.__eq__(point1, point2) automatically (point1 becomes self, point2 becomes other), and the comparison is based on the coordinates you actually care about — self.x == other.x and self.y == other.y — rather than object identity.

This is the general shape of every dunder method: you never call __eq__ by name yourself; you write ordinary-looking code (p1 == p2), and Python routes it to your custom method behind the scenes.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.