Inheritance and Polymorphism · practice
Use Duck Typing
Polymorphism did not require inheritance in the previous lesson. The
That is Python’s everyday style: use an object by what it can do.
A shared protocol without a base class
The classes are unrelated. The loop still has a contract:
promptcan be read;pointscan be read;is_correct(response)returns a.
A set of expected operations like this is often called a protocol. The objects do not need to declare that they follow it.
Why can the loop use both unrelated classes?
The traditional phrase is: if an object walks like a duck and quacks like a duck, code can treat it as a duck. In practice, read that as: ask for the behavior you need, not the family tree.
Inheritance becomes useful when classes also repeat meaningful implementation. The next two lessons first explore an optional capability, then introduce a base only where shared code earns it.
The exercise builds three unrelated objects and a report that never asks their
Task
Write three unrelated classes that one reporting
TextQuestion, ChoiceQuestion, and SurveyItem each provide prompt, points, and is_correct(response). The survey is worth 0 and every response counts as correct.
Write report(items, responses), returning one "<prompt>: correct" or "<prompt>: incorrect" line per item, followed by "Total: <points>".
The report may not ask what class an item has. A new type providing the same protocol must work unchanged.