Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Create an Abstract Base Class and Enforce Method Implementation

Learn to define an abstract base class (ABC) and ensure subclasses implement required methods using abc.ABC and @abstractmethod.

Python practice25 minInheritance & PolymorphismAdvancedLast updated April 8, 2026

Problem statement

You need to design a small class hierarchy for musical instruments. Create an abstract base class Instrument that enforces a play(note) method. Implement two concrete subclasses, Piano and Drum, each providing their own play implementation. Finally, write a helper function get_instrument_sound(kind, note) that returns the string produced by the appropriate instrument's play method. The helper should be case-insensitive for instrument kind and return 'Unknown instrument' for unsupported kinds. This exercise verifies understanding of abstract base classes, method enforcement, overriding, and simple polymorphic use.

Task

Define an abstract base class with an abstract method, implement concrete subclasses that satisfy the contract, and write a factory function that uses polymorphism.

Examples

Piano plays middle C

Input

get_instrument_sound('piano', 'C4')

Output

Piano plays C4

The Piano class implements play; the factory function instantiates Piano and calls play with note 'C4'.

Input format

Function call: get_instrument_sound(kind: str, note: any)

Output format

A string describing the instrument playing the given note (e.g., 'Piano plays C4'), or 'Unknown instrument' for unsupported kinds.

Constraints

Use abc.ABC and @abstractmethod to make Instrument abstract. Subclasses must implement play(self, note). The factory function must be case-insensitive and return 'Unknown instrument' for unknown kinds. Do not use external libraries.

Samples

Sample 1

Input

get_instrument_sound('drum', 'beat')

Output

Drum plays beat

Drum implements play and returns the formatted string.