from abc import ABC, abstractmethod class MessageSender(ABC): # Abstraction @abstractmethod def send(self, message: str) -> None: pass
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() .
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.
class EmailSender(MessageSender): # Low-level def send(self, message: str) -> None: # SMTP logic here pass Python 3- Deep Dive -Part 4 - OOP-
from abc import ABC, abstractmethod class DiscountStrategy(ABC): @abstractmethod def apply(self, amount: float) -> float: pass
import smtplib # Concrete low-level class NotificationService: # High-level def alert(self, message): # Direct dependency on SMTP implementation server = smtplib.SMTP("smtp.gmail.com") server.sendmail(...)
def save_to_db(self): print(f"Saving self.name to DB") # Persistence Deep Dive Issue: Python is not statically typed
from typing import Protocol class Printer(Protocol): def print(self, doc: str) -> None: ...
class Sparrow(FlyingBird): def move(self): return self.fly(100) def fly(self, altitude: int): return f"Flying at altitude"
class EmployeeDiscount(DiscountStrategy): # Extension: No existing code modified def apply(self, amount: float) -> float: return amount * 0.5 class EmailSender(MessageSender): # Low-level def send(self
class Employee: def __init__(self, name, salary): self.name = name self.salary = salary def calculate_pay(self): return self.salary * 0.8 # Business rule
class Bird: def fly(self, altitude: int) -> None: return f"Flying at altitude" class Penguin(Bird): def fly(self, altitude: int) -> None: # Violation: Changes pre-condition (cannot fly) raise NotImplementedError("Penguins can't fly")
class SmsSender(MessageSender): # Another low-level def send(self, message: str) -> None: # Twilio logic here pass
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
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.