Polymorphism in Python
OOP Design
Polymorphism & Duck Typing
Python embraces duck typing: if an object implements the right methods, it can stand in for anything else.
Interfaces
- Use abstract base classes or Protocols to define required methods.
from abc import ABC, abstractmethod
class Notifier(ABC):
@abstractmethod
def send(self, message: str) -> None: ...
Duck typing
Rely on behavior, not type:
def send_all(notifiers: list):
for notifier in notifiers:
notifier.send("Hello")
As long as objects implement .send(), they work.