Part 09 / Topic 12 of 12
Putting it together: bank account system
Real-world example: a small bank with savings and current accounts.
Accountis the parent: it holds the owner, balance and a transaction history list (composition: an account has transactions).SavingsAccountmust keep a minimum balance and earns interest.CurrentAccountallows an overdraft (going below zero up to a limit).- A custom
InsufficientBalanceError(Part 6) stops bad withdrawals. __str__prints a friendly summary.
class InsufficientBalanceError(Exception):
"""Raised when a withdrawal would break the account's rules."""
class Account:
def __init__(self, owner: str, balance: int = 0):
self.owner = owner
self._balance = balance
self.history = [] # list of (kind, amount)
@property
def balance(self) -> int: # read-only from outside
return self._balance
def deposit(self, amount: int) -> None:
if amount <= 0:
raise ValueError("Deposit must be positive")
self._balance += amount
self.history.append(("deposit", amount))
def can_withdraw(self, amount: int) -> bool:
return amount <= self._balance
def withdraw(self, amount: int) -> None:
if not self.can_withdraw(amount):
raise InsufficientBalanceError(
f"{self.owner}: cannot withdraw ₹{amount:,}, balance ₹{self._balance:,}"
)
self._balance -= amount
self.history.append(("withdraw", amount))
def __str__(self) -> str:
sign = "-" if self._balance < 0 else "" # show -₹4,000, not ₹-4,000
return f"{type(self).__name__}({self.owner}, {sign}₹{abs(self._balance):,})"
class SavingsAccount(Account):
MIN_BALANCE = 1000
def can_withdraw(self, amount: int) -> bool: # overriding
return self._balance - amount >= self.MIN_BALANCE
class CurrentAccount(Account):
def __init__(self, owner: str, balance: int = 0, overdraft: int = 5000):
super().__init__(owner, balance)
self.overdraft = overdraft
def can_withdraw(self, amount: int) -> bool:
return self._balance - amount >= -self.overdraft
savings = SavingsAccount("Asha", 5000)
current = CurrentAccount("Ravi Traders", 2000)
for account, amount in [(savings, 4500), (current, 6000)]:
try:
account.withdraw(amount)
except InsufficientBalanceError as e:
print("Declined:", e)
print(savings) # SavingsAccount(Asha, ₹5,000)
print(current) # CurrentAccount(Ravi Traders, -₹4,000)
print(current.history) # [('withdraw', 6000)]
Output of the loop:
Declined: Asha: cannot withdraw ₹4,500, balance ₹5,000
withdraw is written once in Account. Each child only changes the rule in can_withdraw: that is inheritance plus polymorphism.
Full program (with a Transaction dataclass, a StrEnum, interest and a statement): examples/07_bank_account_system.py.
Done here? The practice set for Part 9 — 8 exercises with solutions — is on the part page.