×

python · level 2 · unit 7 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Methods give objects skills, and describes them.

A method is a function inside a class. Its first parameter is always self, so it can read and change the object's attributes. Call it with a dot, like piggy.add(2.5), and Python passes the object in as self for you.

Some methods have names, and Python calls them itself. __init__ was the first. __str__ is another: print calls it to find out what text to show.

Without __str__, printing an object shows an unhelpful label like <__main__.PiggyBank object at 0x...>.

class PiggyBank:
    def __init__(self):
        self.coins = 0
    def add(self, amount):
        self.coins = self.coins + amount
    def __str__(self):
        return f"Piggy bank holding £{self.coins:.2f}"
piggy = PiggyBank()
piggy.add(2.5)
print(piggy)

__str__ must return a string, so return the text rather than printing it.