Interfaces and Polymorphism
Low-Level Design: lesson 4 of 10
Call one method name and let each type answer in its own way.
Lesson 4 of 10 · 5 min
Interfaces and Polymorphism
Step 1 of 11
An interface is a promise about method names, not about data.
The Idea
An interface is a promise about method names, not about data. Anything honouring the promise is interchangeable, so the caller writes one line and each type supplies its own behaviour. Abstract base classes turn that promise into an error you get at construction time rather than in production.
Real-World Example
A power-tool battery platform. One 18V pack runs the drill, the sander and the site radio. Inside, those tools have nothing in common; the contact block is the whole contract, and a new tool joins the family by matching it.
The Code
from abc import ABC, abstractmethod
class Notifier(ABC): # the contract: one method, no data
@abstractmethod
def send(self, msg): ...
class Sms(Notifier):
def send(self, msg): return "sms:" + msg
class Webhook(Notifier):
def send(self, msg): return "post:" + msg
def fan_out(channels, msg): # depends on the contract, not the classes
return [c.send(msg) for c in channels]
print(fan_out([Sms(), Webhook()], "disk full"))
try: Notifier() # abstract: refuses to be built
except TypeError: print("contract only")
Your turn
What does this print?
class Plain:
def tag(self): return "A"
class Loud(Plain):
def tag(self): return "B"
def show(items): return "".join(x.tag() for x in items)
print(show([Plain(), Loud(), Plain()]))Mini quiz
1 / 3