added abc, interfaces and polymorphism
This commit is contained in:
1 parent
6202f69e1c
commit
35db4c9201
4 files changed
+302
-2
No files matched your search
@@ -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}")
|
||||
Reference in new issue
Block a user