__add__

Dunder MethodPython 2.0+Intermediate

Defines behavior for the + addition operator

Quick Info

Documentation
Official Docs
Python Version
2.0+

Learn by Difficulty

Quick Example

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.

Try in Playground

Tags

oopmagic-methodprotocolcore