ABCs
Abstract base classes define interfaces. Subclasses must implement all abstract methods or instantiation raises TypeError.
Abstract base classes define interfaces. Subclasses must implement all abstract methods or instantiation raises TypeError.
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
ABCs document contracts explicitly — subclasses get a TypeError at instantiation, not at runtime call.