This Python __add__ lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
__add__ runs for the + operator. Return a new object. Leave the two originals unchanged unless you have documented a different rule.
The result should be something the caller can add again.
Example 1: Start here
Returning self.value + other.value gives a plain number, and a second addition of Score objects would fail.
class Score: # a template for objects
def __init__(self, value): # runs when you create the object
self.value = value # store this on the object
def __add__(self, other): # define the function; it runs when you call it
return Score(self.value + other.value) # send this value back to the caller
print((Score(80) + Score(2)).value) # plus joins text; use str() for a number
Example 2: Add two objects
__add__ runs when you use the plus sign.
class Money: # a template for objects
def __init__(self, amount): # runs when you create the object
self.amount = amount # store this on the object
def __add__(self, other): # define the function; it runs when you call it
return Money(self.amount + other.amount) # send this value back to the caller
print((Money(20) + Money(4)).amount) # plus joins text; use str() for a number
Example 3: Return the same type
Returning a Money object lets the caller keep using the class.
class Money: # a template for objects
def __init__(self, amount): # runs when you create the object
self.amount = amount # store this on the object
def __add__(self, other): # define the function; it runs when you call it
return Money(self.amount + other.amount) # send this value back to the caller
def __repr__(self): # define the function; it runs when you call it
return "Money(" + str(self.amount) + ")" # send this value back to the caller
print(Money(20) + Money(4)) # plus joins text; use str() for a number
Example 4: Add a number too
isinstance lets the method accept either a Money object or a plain number.
class Money: # a template for objects
def __init__(self, amount): # runs when you create the object
self.amount = amount # store this on the object
def __add__(self, other): # define the function; it runs when you call it
extra = other.amount if isinstance(other, Money) else other # use the value before if when the test is true
return Money(self.amount + extra) # send this value back to the caller
print((Money(20) + 4).amount) # plus joins text; use str() for a number
