python · level 2 · unit 7 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Mum goes for two walks. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Counter:
def __init__(self, name):
self.name = name
self.steps = 0
def walk(self, steps):
self.steps = self.steps + steps
mum = Counter("Mum")
mum.walk(300)
mum.walk(450)
print(mum.name, mum.steps)
your turn
Your turn. Give a parcel a label.
Fill in the dunder method name that print uses. Then send a parcel of your own: who it is for, and how heavy it is in kilograms.
fix it
The team cannot win. Can you fix it?
- Read the error:
winwas given 1 argument but takes none. What does Python pass in by itself? - Python always hands the object to a method as its first argument, so every method needs a
selfparameter. - Change line 5 to def win(self): and run.
nailed it
your objects have skills now. :D
- A method is a function in a class, with
selffirst. - Call a method with a dot, and Python passes
selfin. __str__returns the textprintshows for your object.
new words in your collection
- dunder
- __str__
This lesson isn’t saved. A free account remembers every lesson you finish.