Definition
Abstraction means exposing what something does and hiding how. An Abstract Base Class (ABC) defines methods that subclasses must implement, and can't itself be instantiated. A Protocol describes a required shape without any inheritance.
In simple words
A car's steering wheel hides the engine. An ABC is a contract: anything calling itself a Vehicle must have a drive() method, or Python refuses to create it.
Why it matters
It catches missing methods when an object is created, rather than much later. It also lets you swap one model or database for another without changing the code that calls it.
How it works
In code
from abc import ABC, abstractmethod
class Model(ABC):
@abstractmethod
def predict(self, x):
...
class AlwaysYes(Model):
def predict(self, x):
return "yes"
class Broken(Model):
pass
print(AlwaysYes().predict(1))
for cls in (Model, Broken):
try:
cls()
except TypeError as error:
print(cls.__name__, "can't be created:", "abstract" in str(error))Output
yes Model can't be created: True Broken can't be created: True
Common mistakes
- Forgetting to inherit from ABC, so that @abstractmethod has no effect.
- Building big class hierarchies too early. Add abstraction once you have two real cases.
Check yourself
Summary
- Abstraction hides how, and shows what.
- ABCs enforce required methods.
Finished reading?
Sources: Python docs: abc