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

Using Abstract Base Classes

You will define interfaces using the abc module to enforce that derived classes implement specific required methods.

In this lesson, you will learn how to use Abstract Base Classes (ABCs) to create a blueprint that forces your subclasses to follow specific structural rules.

The Need for Blueprints

When designing a system, you often want to ensure that any class inheriting from a base class implements a specific set of methods. For example, if you are building a system for different payment methods, every payment processor must have a process_payment() method. If a developer creates a new payment class but forgets to include that method, your system will break.

Abstract Base Classes act as a contract, raising an error if a developer tries to create a subclass without implementing the required logic.

Implementing an ABC

To define an ABC, you import the ABC class and the abstractmethod decorator from the abc module. By marking a method as an @abstractmethod, you signal that it is mandatory for any subclass to provide its own version.

from abc import ABC, abstractmethod

class PaymentProcessor(ABC):
    @abstractmethod
    def process_payment(self, amount):
        pass

class CreditCard(PaymentProcessor):
    def process_payment(self, amount):
        print(f"Processing ${amount} via Credit Card.")

# This would cause a TypeError:
# class PayPal(PaymentProcessor):
#     pass 

In the example above, PaymentProcessor cannot be instantiated on its own because it is abstract. Any subclass, like CreditCard, is required to define process_payment. If you attempt to instantiate a class that inherits from PaymentProcessor but fails to implement that method, Python will throw a TypeError immediately, preventing the program from running with missing functionality.

Why use this?

Using ABCs allows you to enforce consistency in large projects. It ensures that no matter who writes a subclass, they are forced to adhere to the interface you defined. It serves as "documentation through code," making it clear exactly what behaviors every implementation of your base class must support.

Key Takeaway: Abstract Base Classes define a mandatory interface for subclasses, ensuring your code remains robust and predictable by preventing the creation of incomplete objects.