0%

Inheritance and Polymorphism · practice

Initialize Subclasses with super()

A subclass with no extra fields can inherit its constructor unchanged. Text and numeric questions need additional state, so they define __init__ themselves.

The shared part must still be initialized once.

Call the base implementation

Try it

super() selects the base implementation for this . The subclass passes the shared fields upward, then stores only its own field.

Without that call, every subclass repeats:

self.prompt = prompt
self.points = points

That duplication is precisely what the base was meant to remove.

Why call super().__init__(prompt, points)?

Subclasses keep only their differences

After the base initializes prompt and points:

  • TextQuestion stores an answer;

  • ChoiceQuestion stores a correct option;

  • NumericQuestion stores an answer and tolerance.

They inherit describe and override is_correct. Calling code still uses one protocol and never asks which subclass it received.

A nonnumeric response still exposes the numeric subtype’s unfinished behavioral contract here. Lesson 8 handles that family-wide promise; this exercise focuses only on correct initialization.

Refactor the three supplied classes so every shared disappears from the subclasses.

Task

Refactor the three question classes to inherit from Question.

The base validates a non-empty prompt and non-negative points, provides describe(), and has an is_correct(response) placeholder raising NotImplementedError.

Each subclass defines __init__, calls super().__init__(prompt, points), and stores only its specific fields. None may reassign shared fields or redefine describe. Text answers and choice options must be non-empty; store choice options normalized. Numeric tolerance must be non-negative.

Keep score_quiz unchanged.