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

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

class SmsSender(MessageSender): # Another low-level def send(self, message: str) -> None: # Twilio logic here pass

class NotificationService: # High-level def (self, sender: MessageSender): # Injected dependency self._sender = sender Python 3- Deep Dive -Part 4 - OOP-

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")

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.

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

class Scanner(Protocol): def scan(self, doc: str) -> None: ...

class FlyingBird(Bird): @abstractmethod def fly(self, altitude: int): pass

from abc import ABC, abstractmethod class Bird(ABC): @abstractmethod def move(self): pass Deep Dive Issue: In Python, it's tempting to

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

from abc import ABC, abstractmethod class DiscountStrategy(ABC): @abstractmethod def apply(self, amount: float) -> float: 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

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

class Sparrow(FlyingBird): def move(self): return self.fly(100) def fly(self, altitude: int): return f"Flying at altitude"