Stop 07 · Object-Oriented ProgrammingTopics · 9/10

Abstract Base Classes

Part of the Python Roadmap

In short

When you design a family of classes that must all provide the same methods, abstract base classes make it official. Forget to implement one and Python stops you right when you try to create the object.

The abc module lets you define an abstract base class with @abstractmethod methods that every subclass must implement. It is a way to enforce a common interface, such as a PaymentMethod with a pay() method.

The jaadu holds out a contract with empty checkboxes to a line of delivery riders on a bike, a cycle and on foot.

Think of it like this

A job contract

Every delivery partner signs the same contract: you must be able to pick up and drop off. How they do it (bike, cycle, on foot) is up to them. An abstract base class is that contract. A class that doesn't fulfil every clause simply isn't allowed to start work.

Watch it happen

PaymentMethod and its implementations

PaymentMethod (abstract)
UPIPayment
CardPayment
HalfDone (missing pay)

1/4PaymentMethod declares pay() and refund() as @abstractmethod. PaymentMethod() itself can't be created.

The big ideas

What you need to know

Inherit from ABC

from abc import ABC, abstractmethod, then class PaymentMethod(ABC): marks it as abstract.

@abstractmethod

Each decorated method must be overridden. Abstract classes can't be instantiated directly.

Shared code allowed

An ABC can still have normal methods that every child inherits, like a receipt() helper.

ABC vs duck typing

Duck typing is flexible. ABCs add a safety net when many people write implementations, like plug-ins or payment providers.

See it in code

Walk through the code

python
1from abc import ABC, abstractmethod2 3class PaymentMethod(ABC):4    @abstractmethod5    def pay(self, amount: float) -> str: ...6 7    @abstractmethod8    def refund(self, amount: float) -> str: ...9 10    def receipt(self, amount: float) -> str:      # shared helper11        return f"Receipt: {self.pay(amount)}"12 13class UPIPayment(PaymentMethod):14    def __init__(self, vpa: str):15        self.vpa = vpa16 17    def pay(self, amount: float) -> str:18        return f"Paid Rs {amount} via {self.vpa}"19 20    def refund(self, amount: float) -> str:21        return f"Refunded Rs {amount} to {self.vpa}"22 23class HalfDone(PaymentMethod):24    def refund(self, amount: float) -> str:25        return "refunded"26 27print(UPIPayment("karan@okbank").receipt(250))28 29for cls in (PaymentMethod, HalfDone):30    try:31        cls()32    except TypeError as err:33        print(err)

1/6Inheriting from ABC turns on the abstract-method checks.

An abstract PaymentMethod, one complete implementation and one incomplete class that Python refuses to create.

Save yourself the pain

Common mistakes

Oops

Forgetting to inherit from ABC, so @abstractmethod is silently ignored.

Do this instead

The class must inherit from ABC (or use ABCMeta) for the check to happen.

Oops

Making an ABC for every two-class relationship.

Do this instead

Use ABCs when you need to guarantee an interface across many implementations. Simple cases are fine with duck typing.

Your mission

Shapes contract

~25 min

Quick check

What happens when you try to instantiate a subclass that hasn't implemented all abstract methods?

Go deeper

  1. 1Create an abstract PaymentMethod class with an abstract pay() method.
  2. 2Implement UPI and Card subclasses and call pay() on both.
  3. 3Try creating a subclass that forgets pay() and read the error.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge