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

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 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.

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 MessageSender(ABC): # Abstraction @abstractmethod def send(self, message: str) -> None: pass

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 Here is a deep technical breakdown of applying

class StandardDiscount(DiscountStrategy): def apply(self, amount: float) -> float: return amount * 0.9

This is an excellent topic. is the cornerstone of maintainable, scalable Object-Oriented Programming. In the context of Python 3: Deep Dive (Part 4) , we move beyond basic syntax into how these principles interact with Python’s dynamic nature, descriptors, metaclasses, and Abstract Base Classes (ABCs). Deep Dive Issue: In Python, it's tempting to

class VIPDiscount(DiscountStrategy): def apply(self, amount: float) -> float: return amount * 0.8

from typing import Protocol class Printer(Protocol): def print(self, doc: str) -> None: ...

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