Python __add__() Magic Method

Syntax

object.__add__(self, other)

Python’s object.__add__(self, other) method returns a new object that represents the sum of two objects. It implements the addition operator + in Python.

We call this a “Dunder Method” for Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.

Example

In the following example, you create a custom class Data and overwrite the __add__() method so that creates a new Data object with the value being the sum of the values of the two operands a and b of type Data.

class Data:

    def __init__(self, value):
        self.value = value
        
    def __add__(self, other):
        return Data(self.value + other.value)


a = Data(40)
b = Data(2)
c = a + b

print(c.value)
# 42

You have defined the dunder method so that the resulting sum of two Data objects is a Data object itself:

print(type(c))
# <class '__main__.Data'>

If you hadn’t defined the __add__() method, Python would’ve raised a TypeError.

How to Resolve TypeError: unsupported operand type(s) for +

Consider the following code snippet where you try to add two custom objects without defining the dunder method __add__():

class Data:

    def __init__(self, value):
        self.value = value


a = Data(40)
b = Data(2)
c = a + b

print(c.value)

Running this leads to the following error message on my computer:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 11, in <module>
    print(a + b)
TypeError: unsupported operand type(s) for +: 'Data' and 'Data'

The reason for this error is that the __add__() dunder method has never been defined—and it is not defined for a custom object by default. So, to resolve the TypeError: unsupported operand type(s) for +, you need to provide the __add__(self, other) method in your class definition as shown previously:

class Data:

    def __init__(self, value):
        self.value = value
        
    def __add__(self, other):
        return Data(self.value + other.value)

Related Video

Advanced Example of Adding Lists in a Custom Class

To use the addition operator on custom objects, you need to define the __add__() dunder method that takes two arguments: self and other and returns the result of self + other. To obtain the result for a custom object, you can use the attributes (data) maintained in this object.

In the following code, you add two baskets together by combining their contents:

class Basket:
    def __init__(self, contents):
        self.contents = contents

    def __add__(self, other):
        return Basket(self.contents + other.contents)

my_basket = Basket(['banana', 'apple', 'juice'])
your_basket = Basket(['bred', 'butter'])

our_basket = my_basket + your_basket
print(our_basket.contents)

The output of this code snippet is the combined basket:

['banana', 'apple', 'juice', 'bred', 'butter']

The code consists of the following steps:

  • Create the class Basket that holds the list contents to store some goods.
  • Define the magic method __add__ that creates a new Basket by combining the list of goods (contents) from the two operand baskets. Note that we rely on the already implemented addition operator on lists, i.e., list concatenation, to actually implement the addition operator for baskets.
  • We create two baskets my_basket and your_basket, and add them together to a new basket our_basket using the defined addition operation.

Python __add__ vs __iadd__

Python provides the operator x += y to add two objects in-place by calculating the sum x + y and assigning the result to the first operands variable name x. You can set up the in-place addition behavior for your own class by overriding the magic “dunder” method __iadd__(self, other) in your class definition.

>>> x = 1
>>> x += 2
>>> x
3

The expression x += y is syntactical sugar for the longer-form x = x + y:

>>> x = 1
>>> x = x + 2
>>> x
3

So, here’s the difference between Python __add__ and Python __iadd__:

If you overwrite the __add__ magic method, you’ll define the semantics of simple Python addition x + y. And if you overwrite the __iadd__ magic method, you’ll define the semantics of in-place Python addition x += y changing the original object x.

Programmer Humor

Question: Why do programmers always mix up Halloween and Christmas?
Answer: Because Oct 31 equals Dec 25.

(If you didn’t get this, read our articles on the oct() and int() Python built-in functions!)

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!