SyntaxStudy
Sign Up
Python Intermediate 4 min read

Abstract Base Classes

ABCs

Abstract base classes define interfaces. Subclasses must implement all abstract methods or instantiation raises TypeError.

Example
from abc import ABC, abstractmethod

class Notifier(ABC):
    @abstractmethod
    def send(self, message: str, recipient: str) -> bool: ...
    @abstractmethod
    def validate_recipient(self, recipient: str) -> bool: ...
    def notify(self, message, recipient):      # concrete method
        if self.validate_recipient(recipient):
            return self.send(message, recipient)
        raise ValueError("Invalid recipient")

class EmailNotifier(Notifier):
    def send(self, message, recipient): return smtp_send(recipient, message)
    def validate_recipient(self, r): return "@" in r
Pro Tip

ABCs document contracts explicitly — subclasses get a TypeError at instantiation, not at runtime call.