__add__Easy Examples

Defines behavior for the + addition operator

Implementing __add__

Basic implementation of __add__ in a class.

python
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)

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

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

__add__ defines behavior for the + addition operator. Implementing it lets you customize how Python interacts with your objects.

__add__ in action

Seeing __add__ called by Python's built-in operations.

python
# How Python calls __add__ automatically
class Demo:
    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        print(f"__add__ was called!")
        return self

d = Demo(42)
# This triggers __add__:
result = d + Demo(1)

Python automatically calls __add__ when you use the corresponding operator or function on your object.

Want to try these examples interactively?

Open Easy Playground