super()
Python · Unit 13: Inheritance
- Full plan
- Python
- 10 exercises
If the child writes its own __init__, it replaces the parent's: the parent's no longer runs, and whatever it used to store doesn't get stored.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, breed):
self.breed = breed
d = Dog("pug")
print(d.breed)
try:
print(d.name)
except AttributeError:
print("It has no name")Prints
pug It has no name
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. Multiple choice
With this code,
print(d.name)gives anAttributeError. Why?3. Complete the code
Complete it so the dog also stores its name.
4. Complete the code
Complete it so it prints: Valeria 3B
5. Predict the output
What does this code print?
6. Find the bug
This program should print Luis Math. Which line has the bug?
7. Multiple choice
Instead of
super().__init__(name), the child could writeself.name = nameagain. Why issuper()better?8. Put the lines in order
Bread on sale costs 30 minus a 5 discount. Put the lines in order so it prints 25.
9. Predict the output
What does this code print?
10. Write the code
Write
Student's__init__: it takesnameandsch, stores the name withsuper()and stores the school inself.school. It should print Leo North High.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.