Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Overload __add__ for a Vector2D

Create a simple 2D vector class and overload the + operator to add vectors component-wise.

Python practice15 minMagic Methods & Operator OverloadingIntermediateLast updated April 11, 2026

Problem statement

You'll implement a Vector2D class representing a point or vector in 2D space with x and y numeric components. Implement the __add__ magic method so that adding two Vector2D instances returns a new Vector2D whose x and y are the component-wise sums. Also implement a readable representation so results display clearly when returned from expressions. The class should not mutate the original operands. For convenience, implement __radd__ or ensure your __add__ works with sum() when given a starting Vector2D(0,0).

Task

Implement __add__ (and a helpful __repr__) so Vector2D objects can be added using the + operator and behave well with sum().

Examples

Add two simple vectors

Input

Vector2D(1, 2) + Vector2D(3, 4)

Output

Vector2D(4, 6)

x components 1+3=4; y components 2+4=6; result is Vector2D(4, 6).

Input format

Each test is a single Python expression that constructs Vector2D instances and uses the + operator.

Output format

Return value is a Vector2D instance; the harness compares its string representation to the expected string.

Constraints

x and y will be numbers (int or float). Preserve immutability: don't change operands during addition. Make __repr__ show values as 'Vector2D(x, y)'.

Samples

Sample 1

Input

Vector2D(-1, 5) + Vector2D(2, -3)

Output

Vector2D(1, 2)

(-1)+2=1 and 5+(-3)=2.