Python __add__() Method
The __add__() Method
Magic methods can control what happens when you use an operator, like +, on your own objects. This is called operator overloading.
Example
Use __add__() to add the age of two Person objects together:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __add__(self, other):
return self.age + other.age
p1 = Person("Emil", 22)
p2 = Person("Tobias", 19)
print(p1 + p2)
Try it Yourself »
Note: Without __add__(), writing p1 + p2 would raise a TypeError, since Python would not know how to add two Person objects.