ZetCode

Python __add__ Method

Last modified November 17, 2026 Python 3.15

The + operator is implemented by the __add__ method. When the left operand cannot handle the operation, Python also tries the right operand's __radd__ method. This article shows how that dispatch works, how to implement addition for custom classes without mutating the operands, and how to handle mixed types and in-place addition.

How the + operator dispatches

For the expression x + y, Python first calls type(x).__add__(x, y). If that returns NotImplemented, or if the type does not define __add__, Python tries type(y).__radd__(y, x). If both attempts fail, the expression raises TypeError. If the right operand's type is a subclass of the left operand's type and overrides __radd__, Python calls the reflected method first, so a subclass can take control of the operation. The built-in types use the same protocol.

builtin_add.py
print(2 + 3)
print(2.5 + 0.5)
print("foo" + "bar")
print([1, 2] + [3, 4])
print((1, 2) + (3,))

Integers and floats produce a number, strings concatenate, and lists and tuples create a new sequence. None of these operations changes the left operand. For mutable sequences, the separate += operator may update the object in place, which is covered below.

$ python builtin_add.py
5
3.0
foobar
[1, 2, 3, 4]
(1, 2, 3)

Vector addition

A custom __add__ should return a new object and leave both operands unchanged. The method receives self and the other operand, so it can check the type of other before accessing its attributes. The following Vector class adds two vectors component by component.

vector_add.py
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        if not isinstance(other, Vector):
            return NotImplemented
        return Vector(self.x + other.x, self.y + other.y)

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


v1 = Vector(2, 4)
v2 = Vector(5, 1)

print(v1 + v2)
print(v1)
print(v2)

v1 + v2 creates a third Vector; v1 and v2 still hold their original values. The method returns NotImplemented for anything that is not a Vector, which lets Python try the other operand's reflected method instead of raising an error immediately.

$ python vector_add.py
Vector(7, 5)
Vector(2, 4)
Vector(5, 1)

Returning NotImplemented

NotImplemented is a singleton value, not an exception. It means "this type does not know how to add that operand, try the reflected operation". Raising NotImplementedError is a different thing: it is an ordinary exception that stops the expression and is not used by the operator protocol.

notimplemented.py
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        if not isinstance(other, Vector):
            return NotImplemented
        return Vector(self.x + other.x, self.y + other.y)

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


v = Vector(2, 4)

print(Vector.__add__(v, 3))

try:
    print(v + 3)
except TypeError as e:
    print(type(e).__name__, e)

try:
    print(3 + v)
except TypeError as e:
    print(type(e).__name__, e)

Calling Vector.__add__ directly shows the sentinel. The expression v + 3 fails after Python tries the integer's reflected method and finds nothing useful. The reverse expression 3 + v also fails, because Vector has no __radd__. The two error messages name the operands in the order Python tried them.

$ python notimplemented.py
NotImplemented
TypeError unsupported operand type(s) for +: 'Vector' and 'int'
TypeError unsupported operand type(s) for +: 'int' and 'Vector'

Reflected addition and sum()

__radd__ makes addition work when the custom object is on the right. It is also required by sum(), which starts with the integer 0 and then adds each item. The method should return NotImplemented for unsupported types, not raise an error.

money_radd.py
class Money:
    def __init__(self, amount, currency="USD"):
        self.amount = round(amount, 2)
        self.currency = currency

    def __add__(self, other):
        if isinstance(other, Money):
            if self.currency != other.currency:
                raise ValueError("currencies differ")
            return Money(self.amount + other.amount, self.currency)
        if isinstance(other, (int, float)):
            return Money(self.amount + other, self.currency)
        return NotImplemented

    def __radd__(self, other):
        if other == 0:
            return self
        return self.__add__(other)

    def __repr__(self):
        return f"Money({self.amount:.2f} {self.currency})"


prices = [Money(10), Money(20), Money(5.5)]
print(sum(prices))
print(7.5 + prices[0])

try:
    print(prices[0] + Money(10, "EUR"))
except ValueError as e:
    print(type(e).__name__, e)

7.5 + prices[0] calls Money.__radd__, which delegates to __add__ for the actual arithmetic. sum(prices) first tries 0 + Money(...); the special case for other == 0 returns the first item unchanged, and the remaining additions produce a single Money result. A mismatched currency is a value error, not an unsupported operation, so it raises ValueError.

$ python money_radd.py
Money(35.50 USD)
Money(17.50 USD)
ValueError currencies differ

Mixing types and validating values

A method can accept more than one operand type, but it should still return NotImplemented for types it does not understand. The following Currency class supports another Currency and a plain number, while rejecting two different currencies with ValueError.

currency_add.py
class Currency:
    def __init__(self, amount, code):
        self.amount = amount
        self.code = code

    def __add__(self, other):
        if isinstance(other, Currency):
            if self.code != other.code:
                raise ValueError(f"cannot add {self.code} and {other.code}")
            return Currency(self.amount + other.amount, self.code)
        if isinstance(other, (int, float)):
            return Currency(self.amount + other, self.code)
        return NotImplemented

    def __repr__(self):
        return f"Currency({self.amount} {self.code})"


usd = Currency(50, "USD")
print(usd + 10)
print(Currency(10, "USD") + 2.5)

try:
    print(usd + Currency(20, "EUR"))
except ValueError as e:
    print(type(e).__name__, e)

print(Currency.__add__(usd, "10"))

usd + 10 and Currency(10, "USD") + 2.5 both keep the currency code. Adding USD and EUR is a domain error, so the method raises instead of returning NotImplemented. Note that bool is a subclass of int, so isinstance(True, int) is true, so this code also accepts currency + True and adds one unit. Exclude bool explicitly if that is not desired.

$ python currency_add.py
Currency(60 USD)
Currency(12.5 USD)
ValueError cannot add USD and EUR
NotImplemented

In-place addition with +=

The += operator first looks for __iadd__. If it exists, it should modify self and return the result, usually self. If it does not exist, or returns NotImplemented, Python falls back to __add__ and rebinds the name to the returned object.

cart_iadd.py
class Cart:
    def __init__(self, items=()):
        self.items = list(items)

    def __add__(self, other):
        if not isinstance(other, list):
            return NotImplemented
        return Cart(self.items + other)

    def __iadd__(self, other):
        if not isinstance(other, list):
            return NotImplemented
        self.items.extend(other)
        return self

    def __repr__(self):
        return f"Cart({self.items})"


cart = Cart(["apple"])
alias = cart

cart += ["bread"]
print(cart)
print(alias)
print(cart is alias)

bigger = cart + ["milk"]
print(bigger)
print(cart is bigger)

Because __iadd__ extends the existing list and returns self, the alias alias sees the change and cart is alias is True. The plain + operator calls __add__, which builds a new Cart; cart is bigger is therefore False. Keeping these two behaviors consistent is important: users expect += to update an object and + to produce a new one.

$ python cart_iadd.py
Cart(['apple', 'bread'])
Cart(['apple', 'bread'])
True
Cart(['apple', 'bread', 'milk'])
False

Best practices

Addition is one of the most frequently overloaded operations, so it should behave like the built-in types:

Source

object.__add__ - Python documentation

object.__radd__ - Python documentation

object.__iadd__ - Python documentation

operator.add - Python documentation

In this article we have implemented addition for custom classes. We have covered the __add__ and __radd__ dispatch order, the difference between NotImplemented and NotImplementedError, mixed-type validation, and in-place addition with __iadd__. For related topics, see Python __iadd__ method, Python __sub__ method, Python add strings, Python add list element, and Python operators.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.