Skip to main content

Python 3- Deep Dive -part 4 - Oop- 【100% TRUSTED】

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

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() . Python 3- Deep Dive -Part 4 - OOP-

class NotificationService: # High-level def (self, sender: MessageSender): # Injected dependency self._sender = sender def save_to_db(self): print(f"Saving self

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. Deep Dive Issue: Python is not statically typed

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