Python 3- Deep Dive -part 4 - Oop- [TOP]
class EmailSender(MessageSender): # Low-level def send(self, message: str) -> None: # SMTP logic here pass
class FlyingBird(Bird): @abstractmethod def fly(self, altitude: int): pass
class Fax(Protocol): def fax(self, doc: str) -> None: ... class SimplePrinter: def print(self, doc: str) -> None: print(f"Printing doc") Multi-function device can compose multiple protocols class MultiFunctionDevice(Printer, Scanner, Fax): def print(self, doc): ... def scan(self, doc): ... def fax(self, doc): ... 5. D: Dependency Inversion Principle (DIP) Depend on abstractions, not concretions. High-level modules should not depend on low-level modules. Deep Dive Issue: Python's dynamic imports and global singletons (e.g., requests.get , open ) often hard-code dependencies, making unit testing impossible. Python 3- Deep Dive -Part 4 - OOP-
class VIPDiscount(DiscountStrategy): def apply(self, amount: float) -> float: return amount * 0.8
class Scanner(Protocol): def scan(self, doc: str) -> None: ... def fax(self, doc):
class Employee: def __init__(self, name, salary): self.name = name self.salary = salary def calculate_pay(self): return self.salary * 0.8 # Business rule
from abc import ABC, abstractmethod class MessageSender(ABC): # Abstraction @abstractmethod def send(self, message: str) -> None: pass High-level modules should not depend on low-level modules
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.