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:
python
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)
Note: Without
__add__(), writingp1 + p2would raise aTypeError, since Python would not know how to add twoPersonobjects.