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

Enforcing Interface Contracts with Abstract Methods

You will prevent instantiation of incomplete classes by marking specific methods as abstract to ensure consistent behavior across subclasses.

In this lesson, you will learn how to enforce a strict "contract" for your subclasses, ensuring that every child class provides its own version of a required method.

The Problem with Inheritance

When you create a base class, you might want to define a common interface that all subclasses must implement. For example, if you are building a PaymentProcessor class, you want to guarantee that every payment method (like CreditCard or PayPal) has a process() method. If a developer creates a new payment type but forgets to define process(), your system could crash.

Enforcing the Contract

We can prevent this by using the abc (Abstract Base Classes) module. By marking a method as an @abstractmethod, you turn your base class into a template that cannot be instantiated. Any subclass that inherits from it must provide its own logic for those abstract methods, or Python will raise an error if you try to create an object from that subclass.

from abc import ABC, abstractmethod

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

class CreditCard(PaymentProcessor):
    def process(self, amount):
        print(f"Processing credit card payment of ${amount}")

# This works fine because CreditCard implements process()
pay = CreditCard()
pay.process(100)

# This would fail:
# class IncompletePayment(PaymentProcessor):
#     pass
# obj = IncompletePayment() # TypeError: Can't instantiate class

Why use this?

By using @abstractmethod, you are setting a "contract." You are essentially telling other programmers (or your future self): "Any class inheriting from this must provide the logic for these specific actions." It moves errors from your application runtime to the moment you try to instantiate the class, making your code much more reliable. Instead of finding out a method is missing when a user tries to checkout, Python will alert you immediately if you try to initialize an incomplete class.

Key Takeaway: Abstract methods act as a mandatory contract, preventing the instantiation of subclasses that fail to implement required functionality.