A Point Class
Write a class Point(x, y) with:
- a readable
repr:repr(Point(1, 2))is"Point(1, 2)", - equality by value:
Point(1, 2) == Point(1, 2)is true, and a point is never equal to a tuple, - it can be used in sets and as a dictionary key (two equal points are the same key),
- addition:
Point(1, 2) + Point(3, 4)is a newPoint(4, 6); adding anything that is not aPointraisesTypeError.
Understand the problem
Revise the special methods first.
Which special method gives repr(p) and what you see when a point is printed in a list?
__str____repr____print__
__repr__ is the developer-friendly text that repr() and the interactive prompt use; printing a list of points also uses it. __str__ is for the end user and falls back to __repr__ when missing.
A class defines __eq__ but no __hash__. What happens when you put its objects in a set?
- Nothing special
- It raises
TypeError: unhashable type - The objects are compared by identity
Python sets __hash__ to None when you define __eq__ without it, because equal objects must have equal hashes. To use the objects in sets or as keys you must define __hash__ too, from the same fields as __eq__.
In __add__(self, other), what should you return when other is not a Point?
NoneNotImplemented- raise
ValueError
Returning the special value NotImplemented tells Python "I do not know how to do this", so it tries the other operand and finally raises TypeError itself. The same applies to __eq__, where it leads to False for unrelated types.
Write the solution
Write the whole class.
class Point:
# Write your code here.
pass
Hint 1: a question to ask yourself
Which fields decide whether two points are equal? Which methods must use exactly those fields?
Hint 2: the shape of the answer
Store self.x and self.y. __repr__ with an f-string. __eq__ compares (x, y) only when other is a Point. __hash__ is hash((self.x, self.y)). __add__ returns a new Point.
Reflect
Solution
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x!r}, {self.y!r})"
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
def __add__(self, other):
if not isinstance(other, Point):
return NotImplemented
return Point(self.x + other.x, self.y + other.y)
What this tests: __init__, __repr__, __eq__, __hash__, __add__, NotImplemented and isinstance.
The equal-implies-same-hash rule: if a == b then hash(a) == hash(b). Always derive both from the same fields. Objects that are used as keys should not change after creation, which is why frozen=True is the usual choice.
__repr__ is for programmers: aim for text that looks like the code that would create the object. !r inside the f-string uses repr for the fields, so strings keep their quotes.
Return a new object from +: a method like __add__ that changes self would surprise everyone (c = a + b must not change a).
Dataclasses (@dataclass(frozen=True)) generate __init__, __repr__, __eq__ and __hash__ for you. Their repr is Point(x=1, y=2), so this task's exact repr still needs your own __repr__. You must know what dataclasses replace.
What an interviewer might ask next: Add __mul__ for multiplying by a number, and __rmul__ so that 2 * p also works. (__rmul__ is called when the left operand does not know how.)
VISIBLE = 3
CASES = [
('result = repr(Point(1, 2))', 'Point(1, 2)', 'a readable repr'),
('result = (Point(1, 2) == Point(1, 2), Point(1, 2) == Point(2, 1))', (True, False), 'equality by value'),
('result = Point(1, 2) + Point(3, 4) == Point(4, 6)', True, 'addition'),
('result = len({Point(1, 2), Point(1, 2), Point(3, 4)})', 2, 'equal points are one set item'),
('result = {Point(0, 0): "origin"}[Point(0, 0)]', 'origin', 'a point as a dictionary key'),
('result = Point(1, 2) == (1, 2)', False, 'a point is not a tuple'),
('result = error_of(lambda: Point(1, 2) + 5)', 'TypeError', 'adding a number is an error'),
('a = Point(1, 1)\nb = a + Point(1, 1)\nresult = (a == Point(1, 1), b is a)', (True, False), 'addition gives a new object'),
('result = repr([Point(1, 2)])', '[Point(1, 2)]', 'a point inside a list'),
]