This module models behavior variation with abstract base classes and overrides.
- Difficulty: Intermediate.
- Estimated Time: 35-50 minutes.
- Prerequisites:
03-advanced/structs-and-classes,03-advanced/constructors-and-invariants. - Cross-Language Lens: Compare virtual dispatch, interfaces, and duck-typed behavior to see how polymorphism changes by language.
python example/main.py- Abstract base classes and required methods.
- Runtime polymorphism through shared base references.
- Overriding concrete behavior in subclasses.
- Aggregating mixed implementations in one list.
- Forgetting to implement required abstract methods.
- Accessing subclass-only state from generic iteration code.
- Replacing polymorphism with
if type(...)checks.
- Python supports inheritance directly, but its runtime makes polymorphism feel more flexible and less rigid than the compiled tracks.
- Compared with Go, the comparison is nominal inheritance versus interface-style behavior; compared with C++, it is less ceremony and less compile-time checking.
- The key lesson is that polymorphism is a design idea first, not just a language feature.
- exercises/01.py: extend shape model with
Triangle. - exercises/02.py: aggregate shapes in
list[Shape].
- exercises/01.py
- Input: triangle base and height.
- Output: computed area through overridden method.
- Edge cases: zero dimensions; decimal dimensions.
- exercises/02.py
- Input: predefined shape objects.
- Output: total area through polymorphic iteration.
- Edge cases: empty shape list; mixed shape types.
- I can define abstract base classes with polymorphic methods.
- I can override behavior in derived classes.
- I can use polymorphic collections safely.
- I completed exercises/01.py.
- I completed exercises/02.py.