Methods

A method is a function written inside a class. Its first parameter is usually self. self is the object you called the method on.

class Cart:
    def __init__(self):
        self.prices = []

    def add(self, price):
        self.prices.append(price)

    def total(self):
        return sum(self.prices)

cart = Cart()
cart.add(40)
cart.add(25)
print(cart.total())

Output:

65

In cart.add(40), Python passes cart as self and 40 as price. The method then adds 40 to this cart's own list.

Methods keep the code that works on the data in the same place as the data. If you later need a rule, such as a check or a limit, there is one place to add it.

In the exercise, finish the raise and description methods.