Define Required Operations with Abstract Base Classes
Core idea
An abstract base class (ABC) describes operations its concrete subclasses must provide. Import ABC and abstractmethod from abc, inherit from ABC and mark a method with @abstractmethod. This decorator marks the operation as abstract; a class with unresolved abstract methods cannot be instantiated. Ordinary concrete methods can be shared as well.
from abc import ABC, abstractmethodclass Exporter(ABC): @abstractmethod def export(self): passclass TextExporter(Exporter): def export(self): return "text"print(TextExporter().export())TextExporter supplies the required operation.
Intentional failure: incomplete subclass
from abc import ABC, abstractmethodclass Reader(ABC): @abstractmethod def read(self): passclass EmptyReader(Reader): passEmptyReader()EmptyReader still has an unresolved abstract method.
Share a concrete operation
from abc import ABC, abstractmethodclass Report(ABC): @abstractmethod def value(self): pass def render(self): return "Total: " + str(self.value())class Count(Report): def value(self): return 6print(Count().render())The shared render method dispatches to the concrete value implementation.
Common mistake
An ABC does not check the correctness of return values or automatically enforce matching method signatures. Test those contracts separately.
Practice
Define an abstract cost() method and two concrete implementations. Confirm an incomplete subclass cannot be instantiated.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Require operations with ABCs
Check your understanding of abstract base classes.
What is printed?
from abc import ABC, abstractmethodclass A(ABC): @abstractmethod def value(self): passclass B(A): def value(self): return 7print(B().value())Which exception is raised by this intentionally incomplete subclass?
from abc import ABC, abstractmethodclass A(ABC): @abstractmethod def read(self): passclass B(A): passB()What is printed?
from abc import ABC, abstractmethodclass A(ABC): @abstractmethod def value(self): pass def text(self): return "count: " + str(self.value())class B(A): def value(self): return 2print(B().text())What does abstractmethod not automatically guarantee?