Inheriting too much, and forgetting super
The first class lets someone call insert on a stack. The second shows what a skipped super().__init__() leaves behind.
Inheritance lets a new class (the subclass) start from an existing class (the parent) and add or change only what is different. super() reaches the parent's version of a method, and isinstance and issubclass ask whether something belongs to a family of classes.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a Shape class with a method area() that returns 0, and subclasses Square(side) and Circle(radius) that override it (use 3.14). Print the areas of a list of one of each.
Write a Vehicle with __init__(self, wheels), and a Car(Vehicle) whose __init__ takes brand, calls super().__init__(4), and stores the brand. Print car.wheels and car.brand.
Use isinstance to write describe(x) that returns "number" for ints and floats, "text" for strings and "other" for anything else. Test describe(True) and explain the result.
Explain it without notes
What is inheritance, and what does class Dog(Animal) mean?
What does super() do, and why call super().__init__() in a subclass?
What is polymorphism? Give an example with inheritance.
When should you not use inheritance?
Expected output
bad stack: [99, 1, 2, 3]
good size: 3 pop: 3
has insert? False
['extra']
False