Reading history

Python Abstract Classes with abc and Protocol

5 min read 1 views

Create abstract base classes in Python with ABC and @abstractmethod, enforce required methods, share template logic, and compare ABCs with typing.Protocol.

When several classes should share the same set of methods, such as every shape having an area() or every payment method having a fee(), you can describe that promise in an abstract base class. Python’s abc module lets you mark methods as abstract, so the base class cannot be created on its own and any subclass that forgets a required method fails immediately instead of crashing later. This lesson also shows Protocol, which checks the same kind of promise without inheritance.

In this lesson you will learn

  • Creating an abstract base class with ABC
  • Marking methods and properties with @abstractmethod
  • What happens when a subclass misses a method
  • Sharing common code in the base class (the template pattern)
  • Structural typing with typing.Protocol

You should know inheritance and polymorphism.

Abstract Methods

from abc import ABC, abstractmethod
import math


class Shape(ABC):
    """Every shape must know its area and name; the base class cannot be created."""

    @abstractmethod
    def area(self) -> float:
        ...

    @property
    @abstractmethod
    def name(self) -> str:
        ...

    def describe(self):                       # a normal method shared by all shapes
        return f"{self.name} with area {self.area():.2f}"


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

    def area(self):
        return math.pi * self.r ** 2

    @property
    def name(self):
        return "circle"


class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2

    @property
    def name(self):
        return "square"


for s in [Circle(1.5), Square(4)]:
    print(s.describe())

try:
    Shape()
except TypeError as e:
    print("TypeError:", e)


class Triangle(Shape):                        # forgot to implement area and name
    pass

try:
    Triangle()
except TypeError as e:
    print("TypeError:", e)

print(isinstance(Square(2), Shape), issubclass(Circle, Shape))

Output

circle with area 7.07
square with area 16.00
TypeError: Can't instantiate abstract class Shape without an implementation for abstract methods 'area', 'name'
TypeError: Can't instantiate abstract class Triangle without an implementation for abstract methods 'area', 'name'
True True
  • class Shape(ABC) makes Shape an abstract base class. @abstractmethod marks area as required: every concrete subclass must provide it.
  • Stacking @property on top of @abstractmethod requires subclasses to provide a property, here name.
  • The base class can still contain normal methods. describe() is written once and works for every shape, because it relies only on area() and name.
  • Shape() raises TypeError: an abstract class cannot be instantiated.
  • Triangle forgot both required members, so Python refused to create it, and the error message names exactly what is missing. The mistake shows up as soon as you create an object, not later when someone calls area().
  • isinstance and issubclass work as usual, so code can check “is this a Shape?”.

Template Methods and Protocols

from abc import ABC, abstractmethod
from typing import Protocol


# An abstract base class can define a template: fixed steps, variable details
class PaymentMethod(ABC):
    def pay(self, amount):
        if amount <= 0:
            raise ValueError("amount must be positive")
        fee = self.fee(amount)
        return f"{self.label()}: {amount} + fee {fee} = {amount + fee} taka"

    @abstractmethod
    def fee(self, amount) -> int: ...

    @abstractmethod
    def label(self) -> str: ...


class Card(PaymentMethod):
    def fee(self, amount):
        return round(amount * 0.02)

    def label(self):
        return "Card"


class MobileWallet(PaymentMethod):
    def fee(self, amount):
        return 0 if amount < 1000 else 10

    def label(self):
        return "Mobile wallet"


for method in [Card(), MobileWallet()]:
    print(method.pay(1500))


# A Protocol checks structure ("duck typing") without inheritance
class Printable(Protocol):
    def to_text(self) -> str: ...


class Invoice:                                # does not inherit from Printable
    def to_text(self):
        return "Invoice #42: 1500 taka"


def print_all(items: list[Printable]):
    for item in items:
        print(item.to_text())


print_all([Invoice()])

Output

Card: 1500 + fee 30 = 1530 taka
Mobile wallet: 1500 + fee 10 = 1510 taka
Invoice #42: 1500 taka
  • PaymentMethod.pay defines the fixed steps: validate the amount, ask for the fee, and build the receipt. Subclasses only fill in the details that differ, fee and label. This is the template method pattern.
  • Adding a new payment type means writing one small class, and the shared checks cannot be forgotten.
  • A Protocol describes the methods an object must have, without requiring inheritance. Invoice never mentions Printable, yet it fits because it has a to_text method.
  • Protocols are checked by type checkers such as mypy, not at run time. They suit “anything with these methods” situations, while ABCs suit families of related classes.

ABC vs Protocol

Abstract base classProtocol
Moduleabctyping
Subclass must inherit?YesNo
Checked whenAt run time, when an object is createdBy a type checker, before running
Can share code?Yes, through normal methodsNot usually
Best forFamilies of classes you controlAccepting any object with the right methods

Common Mistakes

  1. Forgetting to inherit from ABC. Without it, @abstractmethod has no effect and the class can be created.
  2. Misspelling a method name in the subclass, such as are(). The ABC catches this as a missing method, which is one of its main benefits.
  3. Making every class abstract. Use an ABC only when several classes really share an interface.
  4. Putting @abstractmethod above @property. The order must be @property first, then @abstractmethod.

Practice Exercises

Exercise 1. Add a Rectangle(w, h) class to the first example and print its description.

Show answer
class Rectangle(Shape):
    def __init__(self, w, h):
        self.w, self.h = w, h

    def area(self):
        return self.w * self.h

    @property
    def name(self):
        return "rectangle"

print(Rectangle(3, 5).describe())   # rectangle with area 15.00

Exercise 2. Add a Cash payment method with no fee to the second example. What is printed for Cash().pay(500)?

Show answer
class Cash(PaymentMethod):
    def fee(self, amount):
        return 0

    def label(self):
        return "Cash"

print(Cash().pay(500))   # Cash: 500 + fee 0 = 500 taka

Frequently Asked Questions

Can an abstract method have code in it?

Yes. A subclass must still override it, but it can call the base version with super().method() to reuse shared logic.

Are there ready-made abstract classes in Python?

Yes. collections.abc defines Iterable, Sequence, Mapping and others. Inheriting from them gives you some methods for free; for example, a Sequence that defines __getitem__ and __len__ gets __contains__ and index automatically.

Summary

  • Inherit from ABC and use @abstractmethod to define required methods.
  • Abstract classes cannot be instantiated, and incomplete subclasses fail early.
  • Base classes can hold shared logic that calls the abstract methods.
  • Protocol checks for required methods without inheritance.

Next: Python Magic (Dunder) Methods.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *