added abc, interfaces and polymorphism

This commit is contained in:
aman committed 2026-03-30 19:11:22 +02:00
1 parent 6202f69e1c
commit 35db4c9201
4 files changed
+302 -2

No files matched your search

+2 -2
View File
@@ -1,10 +1,10 @@
## TODOs -
### first
- Decorators - done, revisit exercises in 2-3 days
- Decorators - done, revisit exercises
- Error handling - done (try/except/else/finally, custom exceptions, chaining)
- Unpacking — *args, **kwargs, tuple/dict unpacking (already used)
- Abstract base classes — force subclasses to implement methods using abc module
- Abstract base classes (force subclasses to implement methods using abc module) - done
### then (rolling)
+106
View File
@@ -0,0 +1,106 @@
# Create a payment processing system:
# Create an abstract PaymentProcessor class with:
# __init__ takes name (regular, not abstract)
# @abstractmethod process_payment(self, amount) — returns a confirmation string
# @abstractmethod refund(self, amount) — returns a refund confirmation
# @property @abstractmethod transaction_fee — each processor has a different fee
# Regular method process_with_fee(self, amount) — calls process_payment with amount minus the fee
# Create three subclasses:
# CreditCardProcessor — fee is 0.03 (3%)
# PayPalProcessor — fee is 0.05 (5%)
# CryptoProcessor — fee is 0.01 (1%)
from abc import ABC, abstractmethod
class PaymentProcessor(ABC):
def __init__(self, name): # please clarify for me again, what does the name do?
self.name = name
@abstractmethod
def process_payment(self, amount: float) -> str: # can i set int and float here? how?
...
@abstractmethod
def refund(self, amount: float) -> str:
...
@property
@abstractmethod
def transaction_fee(self):
...
def process_with_fee(self, amount):
fee = amount * self.transaction_fee
final_amount = amount - fee
return final_amount
# creating the subclasses
# CreditCardProcessor — fee is 0.03 (3%)
class CreditCardProcessor(PaymentProcessor):
def refund(self, amount: float) -> str:
return f"Your {self.name} refund of: {amount} was processed successfully."
def process_payment(self, amount: float) -> str: # can i set int and float here? how?
return f"Thank you. The {self.name} payment of {amount} was processed successfully."
@property
def transaction_fee(self):
return 0.03
# PayPalProcessor — fee is 0.05 (5%)
class PayPalProcessor(PaymentProcessor):
def refund(self, amount: float) -> str:
return f"Your {self.name} refund of: {amount} was processed successfully."
def process_payment(self, amount: float) -> str: # can i set int and float here? how?
return f"Thank you. The {self.name} payment of {amount} was processed successfully."
@property
def transaction_fee(self):
return 0.05
# CryptoProcessor — fee is 0.01 (1%)
class CryptoProcessor(PaymentProcessor):
def refund(self, amount: float) -> str:
return f"Your {self.name} refund of: {amount} was processed successfully."
def process_payment(self, amount: float) -> str:
return f"Thank you. The {self.name} payment of {amount} was processed successfully."
@property
def transaction_fee(self):
return 0.01
# --- test
# Can't create the abstract class
#p = PaymentProcessor("test") # TypeError!
# Subclasses work
cc = CreditCardProcessor("Visa")
print(cc.process_payment(100)) # "Visa: Processed $100"
print(cc.transaction_fee) # 0.03
print(cc.process_with_fee(100)) # processes $97.00
pp = PayPalProcessor("MyPayPal")
print(pp.transaction_fee) # 0.05
print(pp.process_with_fee(100)) # processes $95.00
# Missing method = error
class BrokenProcessor(PaymentProcessor):
pass
b = BrokenProcessor("oops") # TypeError!
+153
View File
@@ -0,0 +1,153 @@
"""
Python Abstract Base Classes Practice
=======================================
Concepts covered:
1. Abstract Base Classes (ABC) — enforcing method implementation
2. @abstractmethod — methods subclasses MUST implement
3. @property + @abstractmethod — abstract properties
4. Regular methods in ABCs — inherited by subclasses for free
5. The "contract" pattern — designing class hierarchies
"""
from abc import ABC, abstractmethod
# =============================================================================
# 1. ABSTRACT BASE CLASS — PaymentProcessor
# Cannot be instantiated directly. Subclasses MUST implement:
# - process_payment(amount)
# - refund(amount)
# - transaction_fee (property)
# =============================================================================
class PaymentProcessor(ABC):
"""Abstract base class for all payment processors."""
def __init__(self, name: str):
self.name = name
@abstractmethod
def process_payment(self, amount: float) -> str:
"""Subclasses MUST implement — process a payment."""
...
@abstractmethod
def refund(self, amount: float) -> str:
"""Subclasses MUST implement — process a refund."""
...
@property
@abstractmethod
def transaction_fee(self) -> float:
"""Subclasses MUST implement as @property — return fee rate."""
...
def process_with_fee(self, amount: float) -> float:
"""Regular method — inherited by all subclasses."""
fee = amount * self.transaction_fee
final_amount = amount - fee
return final_amount
# =============================================================================
# 2. CONCRETE SUBCLASSES — Each implements all abstract methods
# =============================================================================
class CreditCardProcessor(PaymentProcessor):
"""Credit card payments — 3% fee."""
def process_payment(self, amount: float) -> str:
return f"{self.name}: Processed ${amount:.2f}"
def refund(self, amount: float) -> str:
return f"{self.name}: Refunded ${amount:.2f}"
@property
def transaction_fee(self):
return 0.03
class PayPalProcessor(PaymentProcessor):
"""PayPal payments — 5% fee."""
def process_payment(self, amount: float) -> str:
return f"{self.name}: Processed ${amount:.2f}"
def refund(self, amount: float) -> str:
return f"{self.name}: Refunded ${amount:.2f}"
@property
def transaction_fee(self):
return 0.05
class CryptoProcessor(PaymentProcessor):
"""Crypto payments — 1% fee."""
def process_payment(self, amount: float) -> str:
return f"{self.name}: Processed ${amount:.2f}"
def refund(self, amount: float) -> str:
return f"{self.name}: Refunded ${amount:.2f}"
@property
def transaction_fee(self):
return 0.01
# =============================================================================
# 3. TESTS
# =============================================================================
if __name__ == "__main__":
# --- Can't instantiate abstract class ---
print("=== Abstract Class Protection ===")
try:
p = PaymentProcessor("test")
except TypeError as e:
print(f" Can't create PaymentProcessor: {e}")
# --- CreditCardProcessor ---
print("\n=== CreditCardProcessor (3% fee) ===")
cc = CreditCardProcessor("Visa")
print(f" {cc.process_payment(100)}")
print(f" Fee: {cc.transaction_fee}")
print(f" $100 after fee: ${cc.process_with_fee(100):.2f}")
# --- PayPalProcessor ---
print("\n=== PayPalProcessor (5% fee) ===")
pp = PayPalProcessor("MyPayPal")
print(f" {pp.process_payment(100)}")
print(f" Fee: {pp.transaction_fee}")
print(f" $100 after fee: ${pp.process_with_fee(100):.2f}")
print(f" {pp.refund(50)}")
# --- CryptoProcessor ---
print("\n=== CryptoProcessor (1% fee) ===")
cp = CryptoProcessor("Bitcoin")
print(f" {cp.process_payment(100)}")
print(f" Fee: {cp.transaction_fee}")
print(f" $100 after fee: ${cp.process_with_fee(100):.2f}")
# --- Polymorphism — treat all processors the same ---
print("\n=== Polymorphism ===")
processors = [
CreditCardProcessor("Visa"),
PayPalProcessor("PayPal"),
CryptoProcessor("Ethereum"),
]
for proc in processors:
fee_amount = 100 - proc.process_with_fee(100)
print(f" {proc.name}: ${fee_amount:.2f} fee on $100")
# --- BrokenProcessor — missing methods ---
print("\n=== BrokenProcessor ===")
class BrokenProcessor(PaymentProcessor):
pass
try:
b = BrokenProcessor("oops")
except TypeError as e:
print(f" Can't create BrokenProcessor: {e}")
+41
View File
@@ -0,0 +1,41 @@
---
### **Intermediate (solidify foundation)**
1. Functions & closures
2. Decorators (basic & with arguments)
3. Generators & `yield`
4. Context managers (`with`, `__enter__`, `__exit__`)
5. Exception handling patterns
---
### **Upper-Intermediate**
1. Iterators & custom iterable classes
2. `functools` tools: `partial`, `lru_cache`, `wraps`
3. `*args` / `**kwargs` + argument unpacking mastery
4. Property, `@classmethod`, `@staticmethod`
5. Modules, packages, and import system internals
---
### **Advanced**
1. Metaclasses & class customization
2. Descriptors (`__get__`, `__set__`, `__delete__`)
3. Introspection & reflection (`inspect`, `getattr`, `type`)
4. Async programming (`async`, `await`, `asyncio`)
5. Concurrency: threading, multiprocessing, `concurrent.futures`
6. Memory & performance optimization (`__slots__`, generators, caching)
7. Monkey patching & dynamic code modification
8. C extensions / Cython for speed-critical code
---
| **Stage** | **Project** | **Key Concepts to try** |
| ---------------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| **Intermediate** | Custom Logger with Decorators | Decorators (basic + with arguments), `*args`/`**kwargs`, closures, function introspection, logging I/O |
| **Upper-Intermediate** | Personal Expense Tracker CLI | Classes & OOP, `@property`, `@classmethod`, iterators, context managers, `functools` tools |
| **Advanced** | Async Web Scraper + Cache | Asyncio, `async`/`await`, concurrency (threads/processes), caching (`lru_cache`), memory optimization (`__slots__`), descriptors, introspection |