Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Objects with purpose
EXPERIMENT 46 / 101

Agree on the shape of a tool.

Describe a shared operation and let concrete implementations supply the behaviour.

ADVANCED LAB
BY NAVAN SAMI◷ 11 MIN READPYTHON 3

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.

abstract_interfaces.py
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"))
↳ EXPECTED OUTPUT
Project: Orbit
ORBIT

03 Under the hood

  1. 1

    Formatter declares the operation. The abstractmethod marker means Formatter itself cannot be instantiated as a complete implementation.

  2. 2

    Both concrete classes implement render. The loop only knows that each object can provide that behaviour.

  3. 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

A SMALL MISSION

Create a concrete formatter that renders a project name inside square brackets.

Reveal one possible solution +
one_possible_solution.py
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

QUICK SIGNAL CHECK

What prevents instantiation of an incomplete abstract class?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.