0%

Inheritance and Polymorphism · practice

Use Duck Typing

Polymorphism did not require inheritance in the previous lesson. The cared only that every answered the same operation.

That is Python’s everyday style: use an object by what it can do.

A shared protocol without a base class

Try it

The classes are unrelated. The loop still has a contract:

  • prompt can be read;

  • points can 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 . A fourth type invented by the grader must work without changing the report.

Task

Write three unrelated classes that one reporting can use identically.

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.