CodeBlanks Logo Icon CodeBlanks

__add__

Learn operator overloading with __add__.

The __add__ method

__add__(self, other) defines the + operator. It usually returns a new instance; it does not mutate self. This lets you do math-like operations on class instances.

Example: class Vector:\n def __add__(self, other):\n return Vector(self.x + other.x, self.y + other.y). Writing v1 + v2 returns a new Vector. self.x and other.x are summed; the result goes into a new instance. This gives immutable-style composition.

Return a new instance

__add__ does not mutate self; it returns a new instance. This keeps the original instances intact. After the operation, v1 and v2 stay the same.

Example: after v3 = v1 + v2, v1 and v2 are unchanged; v3 is a new instance. This is the expected behavior for mathematical vectors. If we mutated self, we would have unexpected side effects beyond v1 += v2.

Practice Add __add__ to the Vector class

Define the Vector class. Add def __init__(self, x, y): with self.x = x and self.y = y in the body. Add def __add__(self, other):; in the body write return Vector(self.x + other.x, self.y + other.y). Then call v1 = Vector(1, 2), v2 = Vector(3, 4), v3 = v1 + v2 and print(v3.x).

Starter code

main.py
# Define the Vector class

Sample solution

main.py
# Define the Vector class
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2
print(v3.x)

Expected output

4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the __add__ body

Question
class Vector:
    def __add__(self, other):
        return Vector(self.x + ____, self.y + other.y)
Answer
class Vector:
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

Explanation: other.x is added to self.x.

2 Which method does v1 + v2 call?

  • __mul__
  • __add__ Correct answer
  • __sub__
  • __radd__

Explanation: The + operator calls the __add__ method.

3 Match the __add__ concepts

Term Meaning
__add__ + operator
return Vector(...) New instance
v1 + v2 Operation call

All lessons in Intermediate