Skip to content

Latest commit

 

History

History
60 lines (42 loc) · 1.97 KB

File metadata and controls

60 lines (42 loc) · 1.97 KB

Inheritance and Polymorphism (Python)

This module models behavior variation with abstract base classes and overrides.

Learning Metadata

  • 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.

Quick Run

python example/main.py

Topics Covered

  • Abstract base classes and required methods.
  • Runtime polymorphism through shared base references.
  • Overriding concrete behavior in subclasses.
  • Aggregating mixed implementations in one list.

Common Pitfalls

  • Forgetting to implement required abstract methods.
  • Accessing subclass-only state from generic iteration code.
  • Replacing polymorphism with if type(...) checks.

Cross-Language Notes

  • 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.

Exercise Focus

  • exercises/01.py: extend shape model with Triangle.
  • exercises/02.py: aggregate shapes in list[Shape].

Exercise Specs

  1. exercises/01.py
  • Input: triangle base and height.
  • Output: computed area through overridden method.
  • Edge cases: zero dimensions; decimal dimensions.
  1. exercises/02.py
  • Input: predefined shape objects.
  • Output: total area through polymorphic iteration.
  • Edge cases: empty shape list; mixed shape types.

Checkpoint

  • 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.