""" Python OOP Practice =================== Concepts covered: 1. Classes & __init__ 2. @property & encapsulation 3. Custom exceptions (inheritance from Exception) 4. Composition (Transaction history) 5. Inheritance (SavingsAccount) 6. Dunder methods (__repr__, __str__, __getitem__, __len__, __eq__, __lt__) """ from typing import Optional from datetime import datetime # ============================================================================= # 1. CUSTOM EXCEPTIONS # ============================================================================= class InsufficientFundsError(Exception): """Raised when a withdrawal exceeds the available balance.""" def __init__(self, balance, amount): self.balance = balance self.amount = amount super().__init__(f"Cannot withdraw {self.amount}. Balance is only {self.balance}") # ============================================================================= # 2. COMPOSITION — Transaction class (used by BankAccount) # ============================================================================= class Transaction: """Represents a single bank transaction.""" def __init__(self, type: str, amount: float) -> None: self.type = type self.amount = amount self.timestamp = datetime.now() def __repr__(self): return f"Transaction(type='{self.type}', amount={self.amount}, time={self.timestamp})" # ============================================================================= # 3. BASE CLASS — BankAccount # Demonstrates: @property, encapsulation, composition, custom exceptions # ============================================================================= class BankAccount: """A bank account with balance protection and transaction history.""" def __init__(self, owner: str, balance: Optional[float] = None) -> None: self._owner = owner self.balance = balance if balance is not None else 0 # triggers setter self._history = [] # --- Properties --- @property def balance(self): return self._balance @balance.setter def balance(self, value): if value < 0: raise ValueError("Balance cannot be negative") self._balance = value @property def owner(self): """Read-only property — owner cannot be changed.""" return self._owner # --- Core methods --- def deposit(self, money): self.balance += money self._history.append(Transaction("deposit", money)) return self.balance def withdraw(self, money): if (self.balance - money) >= 0: self.balance -= money self._history.append(Transaction("withdrawal", money)) else: raise InsufficientFundsError(self.balance, money) return self.balance def get_history(self): return self._history # --- Dunder methods --- def __repr__(self): return f"BankAccount('{self.owner}', balance={self.balance})" def __str__(self): return f"{self.owner}'s account — balance: {self.balance}" # ============================================================================= # 4. INHERITANCE — SavingsAccount extends BankAccount # ============================================================================= class SavingsAccount(BankAccount): """A savings account with interest and withdrawal limits.""" def __init__(self, owner, balance=None, interest_rate: float = 0.05): super().__init__(owner, balance) self.interest_rate = interest_rate def apply_interest(self): self.balance += self.balance * self.interest_rate return self.balance def withdraw(self, money): if money >= 1000: print("Transactions above 1000 are not allowed") return self.balance return super().withdraw(money) def __repr__(self): return f"SavingsAccount('{self.owner}', balance={self.balance}, rate={self.interest_rate})" # ============================================================================= # 5. DUNDER METHODS — Classroom (container behavior + comparison) # ============================================================================= class Classroom: """Demonstrates __getitem__, __len__, __eq__, __lt__ for container behavior.""" def __init__(self, teacher: str) -> None: self.teacher = teacher self.students = [] def add_student(self, name: str, grade: float): self.students.append({"name": name, "grade": grade}) def __getitem__(self, key): return self.students[key] def __len__(self): return len(self.students) def __eq__(self, other): return len(self.students) == len(other.students) def __lt__(self, other): return len(self.students) < len(other.students) def __repr__(self): return f"Classroom('{self.teacher}', students={len(self.students)})" def __str__(self): return f"Teacher: {self.teacher}, Students: {self.students}" # ============================================================================= # 6. TESTS — Uncomment sections to test each feature # ============================================================================= if __name__ == "__main__": # --- BankAccount basics --- print("=== BankAccount ===") acc = BankAccount("Alice", 100) print(acc) acc.deposit(50) print(f"After deposit: {acc.balance}") acc.withdraw(30) print(f"After withdraw: {acc.balance}") # --- Custom exception --- print("\n=== InsufficientFundsError ===") try: acc.withdraw(500) except InsufficientFundsError as e: print(e) print(f" Balance: {e.balance}, Attempted: {e.amount}") # --- Property protection --- print("\n=== Property Protection ===") print(f"Owner: {acc.owner}") try: acc.owner = "Bob" except AttributeError: print("Cannot change owner — read-only") try: acc.balance = -50 except ValueError as e: print(f"Cannot set negative balance: {e}") # --- Transaction history --- print("\n=== Transaction History ===") for t in acc.get_history(): print(f" {t}") print(f"Total transactions: {len(acc.get_history())}") # --- SavingsAccount --- print("\n=== SavingsAccount ===") savings = SavingsAccount("Alice", 1000, 0.05) print(repr(savings)) savings.apply_interest() print(f"After interest: {savings.balance}") savings.withdraw(500) print(f"After withdraw: {savings.balance}") savings.withdraw(1500) savings.deposit(200) print(f"After deposit: {savings.balance}") # --- Classroom --- print("\n=== Classroom ===") c1 = Classroom("Mr. Smith") c1.add_student("Alice", 85) c1.add_student("Bob", 92) c1.add_student("Charlie", 78) c2 = Classroom("Ms. Jones") c2.add_student("Diana", 90) print(f"c1[0]: {c1[0]}") print(f"len(c1): {len(c1)}") print(f"c1 == c2: {c1 == c2}") print(f"c1 > c2: {c1 > c2}") print(f"Sorted: {sorted([c1, c2])}")