Abstraction means exposing what something does while hiding how it does it. An abstract base class (ABC) formalises this: it defines a required interface — a contract — that every subclass must implement, but can't itself be instantiated.
Defining a contract
Subclass ABC and mark required methods with @abstractmethod. Any subclass must implement them or it can't be instantiated:
from abc import ABC, abstractmethodclass Shape(ABC):@abstractmethoddef area(self):... # every Shape MUST provide area()class Square(Shape):def __init__(self, side):self.side = sidedef area(self): # fulfils the contractreturn self.side ** 2# Shape() # TypeError — can't instantiate an abstract classSquare(4).area() # 16
Why it helps
An ABC guarantees that every subclass provides the expected methods, so code using them can rely on the interface. It catches "you forgot to implement area()" at object-creation time rather than as a mysterious error later.
Key takeaways
- 01Abstraction exposes what an object does and hides how it does it.
- 02ABC + @abstractmethod define a contract subclasses must fulfil.
- 03An abstract class cannot be instantiated directly.
- 04Missing implementations are caught at instantiation, not later.
- 05It lets you program to an interface, not a concrete implementation.
