Editor

Add Two Points Together

Beginner · Write the code · from Python Operator Overloading: Make Classes Work with +, -, ==

From the lesson: Python Operator Overloading: Make Classes Work with +, -, ==

The + operator means different things in different contexts. 3 + 5 gives you 8. 'hello' + ' world' gives you 'hello world'. [1, 2] + [3, 4] gives you [1, 2, 3, 4]. Same symbol, completely different behavior.

Read the lesson

Create a Point class with x and y attributes. Add __add__ so that adding two points creates a new point with summed coordinates. Add __repr__ that returns 'Point(<x>, <y>)'. Create Point(1, 2) and Point(3, 4), add them together, and print the result.

# Create the Point class with __add__ and __repr__

More Operator Overloading exercises

All Python exercises · 50 practice problems · Object-Oriented Programming quiz