Python Fundamentals ยท Objects, Errors and Generators
Make your own objects work with +, == and print by defining double-underscore methods.
class Money:
def __init__(self, amount):
self.amount = amount
def __add__(self, other): # runs for a + b
return Money(self.amount + other.amount)
def __eq__(self, other): # runs for a == b
return self.amount == other.amount
def __repr__(self): # how the object is shown
return "Money(" + str(self.amount) + ")"
a = Money(5)
b = Money(7)
total = a + b
same = total == Money(12)
print(total, same)Money. Its methods are stored, but none of them run yet.class Money belongs to it.__init__ is stored in Money. It runs only when it is called on an object.__add__ is stored in Money. It runs only when it is called on an object.__eq__ is stored in Money. It runs only when it is called on an object.__repr__ is stored in Money. It runs only when it is called on an object.Money is now defined, ready to make objects from.amount with the value 5 is added to the Money that self points to.__init__(), with self = {} and amount = 7. It gets its own names.amount with the value 7 is added to the Money that self points to.__init__() has finished, so its names are gone. The value it returned, {amount: 7}, is stored in b.amount with the value 12 is added to the Money that self points to.__init__() has finished, so its names are gone.__add__() has finished, so its names are gone. The value it returned, {amount: 12}, is stored in total.amount with the value 12 is added to the Money that self points to.__eq__(), with self = {amount: 12} and other = {amount: 12}. It gets its own names. __init__() has finished, so its names are gone.self.amount == other.amount.__eq__() has finished, so its names are gone. The value it returned, true, is stored in same."Money(" + str(self.amount) + ")".