
class Scanner(Protocol): def scan(self, doc: str) -> None: ...
class SmsSender(MessageSender): # Another low-level def send(self, message: str) -> None: # Twilio logic here pass Python 3- Deep Dive -Part 4 - OOP-
class NotificationService: # High-level def (self, sender: MessageSender): # Injected dependency self._sender = sender A subclass might accept different argument types or
class DiscountCalculator: def calculate(self, amount: float, strategy: DiscountStrategy) -> float: return strategy.apply(amount) Subtypes must be substitutable for their base types. Deep Dive Issue: Python's duck typing hides LSP violations. A subclass might accept different argument types or raise unexpected exceptions. Clients should not be forced to depend on
class Penguin(Bird): def move(self): return "Swimming" # No fly method. Substitutable for Bird. Clients should not be forced to depend on methods they do not use. Deep Dive Issue: Python has no explicit interface keyword. We use Protocol (PEP 544) or multiple ABCs . Fat protocols lead to NotImplementedError stubs.
class MultiFunctionDevice(ABC): @abstractmethod def print(self, doc): pass @abstractmethod def scan(self, doc): pass @abstractmethod def fax(self, doc): pass class SimplePrinter(MultiFunctionDevice): def print(self, doc): ... def scan(self, doc): raise NotImplementedError # Forced dependency def fax(self, doc): raise NotImplementedError
from abc import ABC, abstractmethod class MessageSender(ABC): # Abstraction @abstractmethod def send(self, message: str) -> None: pass