Developing banking methods
I'm considering methods to open or close an account and get the total balance. I'll design a Bank class that will hold customers' accounts and have functions for creating customers, opening and closing accounts, and authenticating users.
Then, I'll add a transaction record for logging purposes. I want to build a BankingSystem CLI to run a loop and prompt the user. It’s important to provide working code with concise explanations, balancing the length of the explanations while keeping the code informative. I'll also include features like unique ID generation.Designing banking classes
I'm sketching out some class structures for a banking system. I have a Transaction class to log activity, capturing details like type, amount, and balance after a transaction.
For accounts, I'm defining an abstract Account class with attributes for account number, owner, balance, and transaction history. I aim to create SavingsAccount and CheckingAccount subclasses for specific functionalities, like applying interest or allowing overdrafts. I also want a Customer class to manage multiple accounts, keeping track of customer IDs and associated accounts.Building the Bank class
I'm working on the Bank class, setting up methods for creating customers and opening accounts. The bank will keep track of customers and their accounts using dictionaries.
I want to include crucial functions like transferring money between accounts. The main function will serve as the CLI, offering options like creating customers, opening accounts, depositing, withdrawing, transferring, showing accounts, and listing customers.
I plan to simplify the implementation, avoiding complex features to keep it user-friendly. I'll also add error handling to manage invalid inputs effectively. I'm focusing on clarity and addressing edge cases, especially for deposits, withdrawals, and transfers.Refining account transfer functionality
I'm thinking about how to manage transfers without double-recording descriptions. I can improve the deposit and withdraw methods by allowing a customizable description, defaulting to "Deposit."
I also want to add string representation methods for better transaction logging. For example, a transaction might display as "2025-11-22 10:23 | DEPOSIT | +100.00 | Balance: 500."
When implementing interest for savings accounts, I’ll add an option in the CLI. If the account isn't a savings account, I want to ensure we handle that gracefully. Time to write the code!Addressing potential initialization issues
I'm spotting a potential bug in the Base Account class. When I call self._record("OPEN", initial_balance, "Account opened"), if the initial_balance is zero, recording a deposit of zero might not be ideal. I could adjust it to record the OPEN event with the initial balance instead.
Also, it's crucial to ensure that self.transactions is defined before calling _record. I’ll make sure to fix the order and then write the complete code, adding if __name__ == "__main__": main() for execution. Time to get coding! Below is a complete example of a simple banking system in Python using OOP principles (encapsulation, inheritance, polymorphism, composition).
Save it as banking_system.py and run it with python banking_system.py.
from abc import ABC, abstractmethod
from datetime import datetime
from typing import Dict, List, Optional
class Transaction:
"""Represents a single transaction on an account."""
def __init__(self, t_type: str, amount: float, description: str, balance_after: float):
self.timestamp = datetime.now()
self.t_type = t_type # e.g. "DEPOSIT", "WITHDRAW", "TRANSFER_OUT", etc.
self.amount = amount
self.description = description
self.balance_after = balance_after
def __str__(self):
time_str = self.timestamp.strftime("%Y-%m-%d %H:%M:%S")
sign = "+" if self.amount >= 0 else "-"
return f"{time_str} | {self.t_type:12} | {sign}{abs(self.amount):.2f} | Balance: {self.balance_after:.2f}"
class Account(ABC):
"""Abstract base class for different types of bank accounts."""
_next_account_number = 1000
def __init__(self, owner: "Customer", initial_balance: float = 0.0):
self.account_number = Account._next_account_number
Account._next_account_number += 1
self.owner = owner
self.balance = float(initial_balance)
self.is_active = True
self.transactions: List[Transaction] = []
self._record_transaction("OPEN", initial_balance, "Account opened")
@abstractmethod
def account_type(self) -> str:
"""Return account type name."""
pass
def deposit(self, amount: float, description: str = "Deposit"):
if amount <= 0:
raise ValueError("Deposit amount must be positive.")
if not self.is_active:
raise RuntimeError("Cannot deposit to an inactive account.")
self.balance += amount
self._record_transaction("DEPOSIT", amount, description)
def withdraw(self, amount: float, description: str = "Withdrawal"):
if amount <= 0:
raise ValueError("Withdrawal amount must be positive.")
if not self.is_active:
raise RuntimeError("Cannot withdraw from an inactive account.")
if amount > self.balance:
raise ValueError("Insufficient funds.")
self.balance -= amount
self._record_transaction("WITHDRAW", -amount, description)
def _record_transaction(self, t_type: str, amount: float, description: str):
tx = Transaction(t_type, amount, description, self.balance)
self.transactions.append(tx)
def print_statement(self):
print(f"\nStatement for {self.account_type()} #{self.account_number} (Owner: {self.owner.name})")
print("-" * 70)
for tx in self.transactions:
print(tx)
print("-" * 70)
print(f"Current balance: {self.balance:.2f}\n")
def __str__(self):
return f"{self.account_type()} #{self.account_number} | Owner: {self.owner.name} | Balance: {self.balance:.2f}"
class SavingsAccount(Account):
"""Savings account with interest."""
def __init__(self, owner: "Customer", initial_balance: float = 0.0, interest_rate: float = 0.01):
super().__init__(owner, initial_balance)
self.interest_rate = interest_rate # e.g. 0.02 for 2%
def account_type(self) -> str:
return "Savings"
def apply_interest(self):
if not self.is_active:
raise RuntimeError("Cannot apply interest to an inactive account.")
if self.balance <= 0:
return # No interest on non-positive balances
interest = self.balance * self.interest_rate
self.balance += interest
self._record_transaction("INTEREST", interest, f"Interest at {self.interest_rate * 100:.2f}%")
class CheckingAccount(Account):
"""Checking account with optional overdraft limit."""
def __init__(self, owner: "Customer", initial_balance: float = 0.0, overdraft_limit: float = 0.0):
super().__init__(owner, initial_balance)
self.overdraft_limit = overdraft_limit # e.g. 200 means balance can go to -200
def account_type(self) -> str:
return "Checking"
def withdraw(self, amount: float, description: str = "Withdrawal"):
if amount <= 0:
raise ValueError("Withdrawal amount must be positive.")
if not self.is_active:
raise RuntimeError("Cannot withdraw from an inactive account.")
if self.balance - amount < -self.overdraft_limit:
raise ValueError("Overdraft limit exceeded.")
self.balance -= amount
self._record_transaction("WITHDRAW", -amount, description)
class Customer:
"""Represents a bank customer."""
_next_customer_id = 1
def __init__(self, name: str):
self.customer_id = Customer._next_customer_id
Customer._next_customer_id += 1
self.name = name
self.accounts: Dict[int, Account] = {}
def add_account(self, account: Account):
self.accounts[account.account_number] = account
def get_accounts_summary(self):
if not self.accounts:
return "No accounts."
lines = [str(acc) for acc in self.accounts.values()]
return "\n".join(lines)
def get_total_balance(self) -> float:
return sum(acc.balance for acc in self.accounts.values())
def __str__(self):
return f"Customer #{self.customer_id}: {self.name} | Accounts: {len(self.accounts)} | Total balance: {self.get_total_balance():.2f}"
class Bank:
"""Main Bank class that manages customers and accounts."""
def __init__(self, name: str):
self.name = name
self.customers: Dict[int, Customer] = {}
self.accounts: Dict[int, Account] = {}
# --- Customer operations ---
def create_customer(self, name: str) -> Customer:
customer = Customer(name)
self.customers[customer.customer_id] = customer
return customer
def get_customer(self, customer_id: int) -> Customer:
if customer_id not in self.customers:
raise KeyError("Customer not found.")
return self.customers[customer_id]
# --- Account operations ---
def open_savings_account(self, customer_id: int, initial_balance: float = 0.0, interest_rate: float = 0.01) -> SavingsAccount:
customer = self.get_customer(customer_id)
account = SavingsAccount(customer, initial_balance, interest_rate)
customer.add_account(account)
self.accounts[account.account_number] = account
return account
def open_checking_account(self, customer_id: int, initial_balance: float = 0.0, overdraft_limit: float = 0.0) -> CheckingAccount:
customer = self.get_customer(customer_id)
account = CheckingAccount(customer, initial_balance, overdraft_limit)
customer.add_account(account)
self.accounts[account.account_number] = account
return account
def get_account(self, account_number: int) -> Account:
if account_number not in self.accounts:
raise KeyError("Account not found.")
return self.accounts[account_number]
def close_account(self, account_number: int):
account = self.get_account(account_number)
if not account.is_active:
raise RuntimeError("Account is already inactive.")
if account.balance != 0:
raise RuntimeError("Account balance must be zero to close.")
account.is_active = False
account._record_transaction("CLOSE", 0, "Account closed")
# --- Money operations ---
def transfer(self, from_acc_no: int, to_acc_no: int, amount: float):
if amount <= 0:
raise ValueError("Transfer amount must be positive.")
from_acc = self.get_account(from_acc_no)
to_acc = self.get_account(to_acc_no)
if not from_acc.is_active or not to_acc.is_active:
raise RuntimeError("Both accounts must be active for transfer.")
from_acc.withdraw(amount, description=f"Transfer to {to_acc.account_number}")
to_acc.deposit(amount, description=f"Transfer from {from_acc.account_number}")
# --- Utility ---
def list_customers(self):
if not self.customers:
print("No customers.")
return
for c in self.customers.values():
print(c)
def list_accounts(self):
if not self.accounts:
print("No accounts.")
return
for a in self.accounts.values():
print(a)
# ---------------------- Simple CLI Interface ---------------------- #
def print_menu():
print("\n=== Banking System Menu ===")
print("1. Create new customer")
print("2. Open savings account")
print("3. Open checking account")
print("4. Deposit")
print("5. Withdraw")
print("6. Transfer between accounts")
print("7. Apply interest to savings account")
print("8. Show account statement")
print("9. List customers")
print("10. List accounts")
print("0. Exit")
def main():
bank = Bank("Sample Bank")
while True:
print_menu()
choice = input("Enter your choice: ").strip()
try:
if choice == "1":
name = input("Customer name: ").strip()
customer = bank.create_customer(name)
print(f"Created customer #{customer.customer_id} ({customer.name})")
elif choice == "2":
cid = int(input("Customer ID: "))
initial = float(input("Initial deposit: "))
rate = float(input("Interest rate (e.g. 0.02 for 2%): "))
acc = bank.open_savings_account(cid, initial, rate)
print(f"Opened savings account #{acc.account_number} for {acc.owner.name}")
elif choice == "3":
cid = int(input("Customer ID: "))
initial = float(input("Initial deposit: "))
overdraft = float(input("Overdraft limit: "))
acc = bank.open_checking_account(cid, initial, overdraft)
print(f"Opened checking account #{acc.account_number} for {acc.owner.name}")
elif choice == "4":
acc_no = int(input("Account number: "))
amt = float(input("Deposit amount: "))
acc = bank.get_account(acc_no)
acc.deposit(amt)
print(f"Deposited {amt:.2f} to account #{acc_no}, new balance: {acc.balance:.2f}")
elif choice == "5":
acc_no = int(input("Account number: "))
amt = float(input("Withdrawal amount: "))
acc = bank.get_account(acc_no)
acc.withdraw(amt)
print(f"Withdrew {amt:.2f} from account #{acc_no}, new balance: {acc.balance:.2f}")
elif choice == "6":
from_acc = int(input("From account number: "))
to_acc = int(input("To account number: "))
amt = float(input("Transfer amount: "))
bank.transfer(from_acc, to_acc, amt)
print(f"Transferred {amt:.2f} from #{from_acc} to #{to_acc}")
elif choice == "7":
acc_no = int(input("Savings account number: "))
acc = bank.get_account(acc_no)
if not isinstance(acc, SavingsAccount):
print("This is not a savings account.")
else:
before = acc.balance
acc.apply_interest()
print(f"Interest applied. Old balance: {before:.2f}, new balance: {acc.balance:.2f}")
elif choice == "8":
acc_no = int(input("Account number: "))
acc = bank.get_account(acc_no)
acc.print_statement()
elif choice == "9":
bank.list_customers()
elif choice == "10":
bank.list_accounts()
elif choice == "0":
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()
If you want, I can also strip the CLI and show only the class design, or extend this to load/save data from files (persistence) or add authentication (PINs/passwords).