Skip to main content
Albero Academy

Abstraction

Define contracts with abstract base classes and hide implementation detail.

Object-Oriented Programming9 min

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:

abstract base class
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
... # every Shape MUST provide area()
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self): # fulfils the contract
return self.side ** 2
# Shape() # TypeError — can't instantiate an abstract class
Square(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

  1. 01Abstraction exposes what an object does and hides how it does it.
  2. 02ABC + @abstractmethod define a contract subclasses must fulfil.
  3. 03An abstract class cannot be instantiated directly.
  4. 04Missing implementations are caught at instantiation, not later.
  5. 05It lets you program to an interface, not a concrete implementation.

Finished this chapter?

Mark it complete to track your progress through Python.