Python 3- Deep Dive -part 4 - Oop- Info

def save_to_db(self): print(f"Saving self.name to DB") # Persistence

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.

Here is a deep technical breakdown of applying principles in advanced Python OOP. 1. S: Single Responsibility Principle (SRP) A class should have only one reason to change. Deep Dive Issue: In Python, it's tempting to add save() , load() , or generate_report() methods directly into a data class because of how easy dynamic attributes are. Python 3- Deep Dive -Part 4 - OOP-

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 dataclasses import dataclass @dataclass class Employee: name: str salary: float Responsibility 2: Business logic class PayCalculator: def calculate(self, emp: Employee) -> float: return emp.salary * 0.8 Responsibility 3: Persistence class EmployeeRepository: def save(self, emp: Employee) -> None: # Uses SQLAlchemy, filesystem, etc. pass 2. O: Open/Closed Principle (OCP) Classes should be open for extension, but closed for modification. Deep Dive Issue: Python is not statically typed. Without ABC or Protocol , developers often write long if/elif chains checking type() . def save_to_db(self): print(f"Saving self

class NotificationService: # High-level def (self, sender: MessageSender): # Injected dependency self._sender = sender

from abc import ABC, abstractmethod class DiscountStrategy(ABC): @abstractmethod def apply(self, amount: float) -> float: pass def fax(self, doc):

class DiscountCalculator: def calculate(self, customer_type, amount): if customer_type == "standard": return amount * 0.9 elif customer_type == "vip": return amount * 0.8 elif customer_type == "employee": # Modification needed here return amount * 0.5

class EmployeeDiscount(DiscountStrategy): # Extension: No existing code modified def apply(self, amount: float) -> float: return amount * 0.5