Course contentsShow
← Python
Lesson 481 of 1,0607. Object-Oriented ProgrammingFree lesson

Defining Interfaces with Abstract Base Classes

Utilize the abc module to enforce strict structural contracts and ensure subclasses implement required methods for consistent polymorphic behavior.

In this lesson, you will learn how to use the abc module to enforce strict structural contracts, ensuring that your subclasses provide specific methods to guarantee consistent polymorphic behavior.

Why Interfaces Matter

In large systems, you often need to define a "blueprint" for a set of related classes. For example, if you are building a system that processes different file formats, you want to ensure that every Processor class implements a load() and save() method. Without a contract, a developer might accidentally forget to implement one of these methods, leading to AttributeError crashes at runtime.

Enforcing Contracts with ABC

Python provides the abc (Abstract Base Classes) module to solve this. By inheriting from ABC and marking methods with the @abstractmethod decorator, you turn your class into an interface that cannot be instantiated. If a subclass fails to override these methods, Python will prevent it from being initialized.

from abc import ABC, abstractmethod

class DataProcessor(ABC):
    @abstractmethod
    def process(self, data):
        pass

class JSONProcessor(DataProcessor):
    def process(self, data):
        return f"Processing JSON: {data}"

# This would raise a TypeError because 'process' is missing:
# class TextProcessor(DataProcessor):
#     pass 

processor = JSONProcessor()
print(processor.process({"id": 1}))

Ensuring Consistency

By using ABC, you create a "must-implement" requirement for your architecture. This is powerful for polymorphism; any function that expects a DataProcessor can now safely call .process() on any object passed to it, knowing with 100% certainty that the method exists. This structural rigor transforms runtime "method not found" errors into immediate developer feedback during subclass definition.

The goal here isn't just to group methods, but to create a reliable API surface that your internal system can depend on, regardless of which specific subclass is injected at runtime.

Key Takeaway: Abstract Base Classes use the @abstractmethod decorator to create structural contracts, ensuring that subclasses are forced to implement required methods, thereby guaranteeing safe and predictable polymorphic behavior.