Inheriting
Python · Unit 13: Inheritance
- Full plan
- Python
- 10 exercises
Sometimes one class is a special case of another: a dog is an animal. Instead of copying the code, the new class inherits from the other one.
You write the class it inherits from in parentheses: class Dog(Animal):. Animal is the parent class and Dog is the child. The child gets all of the parent's methods.
class Animal:
def eat(self):
print("Yum")
class Dog(Animal):
pass
rex = Dog()
rex.eat()Prints
Yum
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. Complete the code
Complete it so that
Catinherits fromAnimal.2. Predict the output
What does this code print?
3. Multiple choice
In
class Bike(Vehicle):, what is each one?4. Predict the output
What does this code print?
5. Find the bug
Ana and Leo both have smartphones and both take a photo. It should print click click. Which line has the bug?
6. Predict the output
What does this code print?
7. Find the bug
This program should print Tom meows. Which line has the bug?
8. Put the lines in order
Put the lines in order so it prints: Nemo swims
9. Predict the output
Sofia opens a savings account with 200. What does it print?
10. Predict the output
A child can also be the parent of another class. 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.