Methods
Python · Unit 12: Classes and objects
- Full plan
- Python
- 11 exercises
A method is a function that lives inside the class. Like __init__, it first receives self, so it can use the object's data.
You call it with a dot: luna.greet(). You already know a few: items.append(5) and text.upper() are methods.
class Pet:
def __init__(self, name):
self.name = name
def greet(self):
print("I'm", self.name)
luna = Pet("Luna")
luna.greet()Prints
I'm Luna
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Complete the code
Complete it so the robot says its name.
3. Find the bug
This program should print Woof! Which line has the error?
4. Predict the output
What does this code print?
5. Multiple choice
What does the
passedmethod do?6. Predict the output
What does this code print?
7. Find the bug
This program should print 50. Which line has the error?
8. Complete the code
Every fall costs the cat one life. Complete it so it prints 5.
9. Put the lines in order
Put the lines in order so the cart keeps what you add to it, in that order.
10. Find the case that fails
avg(grades)creates aStudentwith those grades and returns their average. With no grades, it should return 0. Which call does it fail on?11. Predict the output
The thermos holds 600 ml and each cup takes 250. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.