Agree on the shape of a tool.
Describe a shared operation and let concrete implementations supply the behaviour.
01 The idea
Polymorphism lets a caller use different objects through a shared operation. An abstract base class can make that expectation explicit and prevent instantiation until required abstract methods are implemented. Python also supports structural approaches such as protocols and ordinary duck typing; choose the smallest mechanism that communicates the contract.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
from abc import ABC, abstractmethod
class Formatter(ABC):
@abstractmethod
def render(self, name):
raise NotImplementedError
class PlainFormatter(Formatter):
def render(self, name):
return f"Project: {name}"
class LoudFormatter(Formatter):
def render(self, name):
return name.upper()
for formatter in [PlainFormatter(), LoudFormatter()]:
print(formatter.render("Orbit"))Project: Orbit ORBIT
03 Under the hood
- 1
Formatter declares the operation. The abstractmethod marker means Formatter itself cannot be instantiated as a complete implementation.
- 2
Both concrete classes implement render. The loop only knows that each object can provide that behaviour.
- 3
A shared method name is not enough to guarantee compatible semantics. Document inputs, outputs, errors, and side effects, then use contract tests where implementations can differ.
04 Your turn, builder
Create a concrete formatter that renders a project name inside square brackets.
Reveal one possible solution +
from abc import ABC, abstractmethod
class Formatter(ABC):
@abstractmethod
def render(self, name): raise NotImplementedError
class Brackets(Formatter):
def render(self, name): return f"[{name}]"
print(Brackets().render("Orbit"))05 Check your signal
What prevents instantiation of an incomplete abstract class?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.