Published on

What is Python's `__add__` method?

Authors
  • avatar
    Name
    hwahyeon
    Twitter

The __add__ method is a special method corresponding to the addition operator (+). When called, it returns a new value without changing the original variable.

Example Code

a = 1004
a.__add__(5)
print(a)             # Output: 1004
print(a.__add__(5))  # Output: 1009

In this code, a.__add__(5) returns 1009, which is the result of 1004 + 5, but the value of a itself remains 1004. To change a, you need to assign it directly, like a = a + 5.

Special Methods

In Python, all data types are defined as classes. For example, integers are instances of the int class. When you declare a = 1004, a becomes an instance of the int class, and the __add__ method is called automatically when you use the + operator.

For example:

a = 1004
b = 5
print(a + b)  # Output: 1009

In this case, a + b internally calls a.__add__(b) to perform the calculation.

Overloading the __add__ Method

The __add__ method can be overloaded. For instance, you can define __add__ to enable the addition of two vectors:

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)  # Output: Vector(4, 6)

In this code, the __add__ method is overloaded, allowing the + operator to easily compute the sum of vectors.