—
Implement value equality for a mutable class
Tutor me on https://mlprep.iwase.dev/item/prog-py-point-equality/. This is a screening item. If window.mlPrepAgent is available, read attempts for item prog-py-point-equality before tutoring. Inspect my attempt, keep the item ID, and do not reveal the full answer first. After a real attempt, append its record with recorded_by agent, include agent_session_id when available, and read it back.Problem
Implement Point(x, y) with public coordinates, a mutating
translate(dx, dy) method, and value equality between Point instances.
Equality with an unrelated type must not raise an exception. Then explain
the result of point_report().
Reveal answer or reference solution
__eq__ compares both coordinates when the other object is a Point and
returns NotImplemented otherwise. Two distinct points initially have
equal values but different identities. Translating p also changes its
alias, not q, so p != q afterward while p is alias remains true.
class Point:
def __init__(self, x: int, y: int) -> None:
self.x = x
self.y = y
def translate(self, dx: int, dy: int) -> None:
self.x += dx
self.y += dy
def __eq__(self, other: object) -> bool:
if not isinstance(other, Point):
return NotImplemented
return self.x == other.x and self.y == other.y
def point_report() -> tuple[object, ...]:
point = Point(1, 2)
equal_point = Point(1, 2)
alias = point
before = (point == equal_point, point is equal_point, point == alias)
point.translate(1, -1)
after = (point == equal_point, point is alias)
return before, after, (point.x, point.y), (equal_point.x, equal_point.y)Public tests
point_report()→((True, False, True), (False, True), (2, 1), (1, 2))Point(0, 0) == Point(0, 0)→TruePoint(0, 0) == (0, 0)→False
Previous attempts
Loading attempts saved in this browser…