Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 09 / Topic 9 of 12

Abstract classes: abc.ABC and @abstractmethod

An abstract class is a parent that is only a plan. You cannot make objects from it directly. It lists methods that every child must write.

  • Inherit from ABC (from the abc module, "abstract base classes").
  • Mark the required methods with @abstractmethod.
  • A child that does not write them cannot be created either.

Think of a job description: it lists the duties, and each person hired must actually do them.

Real-world example: every shape must know its area.

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self) -> float:
        """Every shape must return its area."""

    def describe(self) -> str:               # normal method, shared by all
        return f"{type(self).__name__} with area {self.area():.2f}"

class Rectangle(Shape):
    def __init__(self, length: float, width: float):
        self.length = length
        self.width = width

    def area(self) -> float:
        return self.length * self.width

class Circle(Shape):
    def __init__(self, radius: float):
        self.radius = radius

    def area(self) -> float:
        return 3.14159 * self.radius ** 2

for shape in [Rectangle(4, 5), Circle(1)]:
    print(shape.describe())
# Rectangle with area 20.00
# Circle with area 3.14

try:
    Shape()
except TypeError as e:
    print(e)
# Can't instantiate abstract class Shape without an implementation for
# abstract method 'area' (printed on one line)

Use an abstract class when several classes must follow the same "contract" and you want Python to catch a missing method early.

Full program (abstract payment methods plus duck typing from section 7): examples/05_payment_methods.py.

๐Ÿ” Going deeper: the docstring alone is a valid body for the abstract method. You may also write ... or pass. type(self).__name__ gives the name of the object's real class.

Read more: the official abc documentation.

Done here? The practice set for Part 9 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide