Write a Python program to simulate a banking system with OOP principles.
- User
Write a Python program to simulate a banking system with OOP principles.
Assistant
1. Understand the Goal: The user wants a Python program that simulates a banking system using Object-Oriented Programming (OOP) principles.
-
Identify Key Components of a Banking System:
- Accounts: The core entity. Needs attributes like account number, holder name, balance, and maybe a PIN for security.
- Operations: Deposit, Withdraw, Check Balance, Transfer (optional but good for complexity), Transaction History (optional but good).
- Bank/Manager: An entity to manage multiple accounts (create accounts, find accounts).
- User Interface (CLI): A way for the user to interact with the system.
-
Determine OOP Principles to Apply:
- Encapsulation: Hiding internal data (like balance) and providing methods (get_balance, deposit) to access/modify it. Using private attributes (e.g.,
self._balance). - Abstraction: Showing only necessary details (e.g.,
deposit()hides the logic of checking validity and updating the balance). - Inheritance (Optional but good): Maybe a base
Accountclass and specific types likeSavingsAccount(interest) orCurrentAccount(overdraft). - Polymorphism: Different account types handling
withdrawdifferently (e.g., overdraft vs. insufficient funds).
- Encapsulation: Hiding internal data (like balance) and providing methods (get_balance, deposit) to access/modify it. Using private attributes (e.g.,
-
Drafting the Class Structure:
-
Class
BankAccount:- Attributes: Account Number, Owner, Balance, Transaction List.
- Methods:
__init__,deposit(),withdraw(),get_balance(),get_details(),_log_transaction()(internal helper).
-
Class
Bank:- Attributes: Dictionary of accounts (mapping ID to Account object).
- Methods:
create_account(),get_account(),transfer_money().
-
-
Refining the Implementation (Mental Code Walkthrough):
- Security: Real banking systems use hashed passwords. For a simulation, a simple PIN check is enough.
- Input Handling: Need a loop (While True) for the menu.
- Error Handling: What if the account doesn't exist? What if the balance is too low? (Use
try...exceptor return values).
-
Step-by-Step Implementation Plan:
- Step 1: The
Transactionclass (optional but cleaner): Keeps track of time, type, amount. - Step 2: The
BankAccountclass:_balance: Make it "protected" (convention) or private.deposit: Must be positive.withdraw: Must have sufficient funds.
- Step 3: The
Bankclass: Manages the collection of accounts. - Step 4: The
Mainexecution loop: A text-based menu.
- Step 1: The
-
Adding Inheritance (to make it a stronger OOP example):
- Let's make
BankAccountthe base class. - Let's make
SavingsAccountwhich adds interest. - Let's make
CheckingAccountwhich allows overdraft (maybe too complex for a basic example? Let's stick to a robust base implementation or maybe just one type to keep it readable, or show inheritance with aSavingsAccount). - Decision: Let's stick to a robust
BankAccountandBankclass structure first. Inheritance can be shown by extendingBankAccountif needed, but for a general request, solid composition and encapsulation are more important. Actually, let's keep it simple but solid: One genericAccountclass is usually enough for a "simulate a banking system" prompt unless specified otherwise. Self-correction: I will add aSavingsAccountchild class to demonstrate Inheritance.
- Let's make
-
Writing the Code (Mental Draft & Refinement):
-
Imports:
datetime,random(for account numbers). -
Class
Account:__init__(self, name, pin)deposit(self, amount)-> Success/Failwithdraw(self, amount)-> Success/Failcheck_balance(self)change_pin(self)
-
Class
Bank:accounts = {}create_account()-> generates ID, createsAccountobject, stores it.login()-> verifies ID and PIN.
-
-
Refining the Code Structure for the Output:
- Use docstrings.
- Use specific exception handling (ValueError for bad input).
- Make the main loop user-friendly.
-
Final Polish:
- Check for edge cases: withdrawing negative money?
- Formatting currency (2 decimal places).
-
Constructing the Explanation:
- Explain the classes.
- Explain the OOP concepts used (Encapsulation, Abstraction).
- Provide instructions on how to run it.
(Self-Correction during coding): I should make sure the
Bankclass handles the account number generation so it's unique. I'll use a simple random integer.Let's write the Python code.
- Class
BankAccount:- Attributes:
account_number,account_holder,__balance(private),__pin. - Methods:
deposit,withdraw,verify_pin,display_balance.
- Attributes:
- Class
Bank:- Attributes:
__accounts(dictionary). - Methods:
create_account,access_account(login logic).
- Attributes:
- Main execution:
- A loop presenting options: Open Account, Access Account, Exit.
Let's execute this plan. Here is a complete, executable Python program that simulates a banking system.
This solution applies three major OOP principles:
- Encapsulation: We hide internal data (like the balance) and protect it from direct outside modification using getter/setter logic.
- Abstraction: The user interacts with simple methods like
deposit()without needing to know how the balance is calculated or stored. - Inheritance: We create a specific type of account (Savings Account) that inherits behavior from the base Account but adds unique functionality (Interest).
The Python Code
import datetime import random # --- 1. BASE CLASS: BankAccount --- class BankAccount: def __init__(self, account_holder, initial_balance=0.0): # Encapsulation: Attributes are 'protected' (denoted by _) self._account_number = self._generate_account_number() self._account_holder = account_holder self._balance = initial_balance self._transactions = [] # List to store history self._log_transaction("Account Created", initial_balance) def _generate_account_number(self): """Helper method to generate a random 8-digit account number.""" return str(random.randint(10000000, 99999999)) def _log_transaction(self, type, amount): """Internal method to record history.""" timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") self._transactions.append({ "time": timestamp, "type": type, "amount": amount, "balance_after": self._balance }) # Abstraction: Public interface to interact with the object def deposit(self, amount): if amount > 0: self._balance += amount self._log_transaction("Deposit", amount) print(f"Deposited ${amount:.2f}. New Balance: ${self._balance:.2f}") else: print("Deposit amount must be positive.") def withdraw(self, amount): if amount <= 0: print("Withdrawal amount must be positive.") elif amount > self._balance: print("Transaction failed: Insufficient funds.") else: self._balance -= amount self._log_transaction("Withdrawal", amount) print(f"Withdrew ${amount:.2f}. New Balance: ${self._balance:.2f}") def get_balance(self): return self._balance def get_account_info(self): return f"Account: {self._account_number} | Holder: {self._account_holder} | Balance: ${self._balance:.2f}" def print_statement(self): print(f"\n--- Statement for {self._account_holder} ---") print(f"{'Time':<20} | {'Type':<15} | {'Amount':<10} | {'Balance':<10}") print("-" * 65) for t in self._transactions: print(f"{t['time']:<20} | {t['type']:<15} | ${t['amount']:<9.2f} | ${t['balance_after']:<9.2f}") print("-" * 65) # --- 2. DERIVED CLASS: SavingsAccount --- # Demonstrates Inheritance and Polymorphism class SavingsAccount(BankAccount): def __init__(self, account_holder, initial_balance=0.0, interest_rate=0.03): # Call the parent constructor super().__init__(account_holder, initial_balance) self._interest_rate = interest_rate # New attribute specific to SavingsAccount # New method specific to this class def apply_interest(self): interest = self._balance * self._interest_rate self._balance += interest self._log_transaction("Interest Applied", interest) print(f"Interest applied! ${interest:.2f} added. New Balance: ${self._balance:.2f}") # Polymorphism: Overriding get_account_info to include rate def get_account_info(self): base_info = super().get_account_info() return f"{base_info} | Type: Savings (Rate: {self._interest_rate*100}%)" # --- 3. SYSTEM MANAGER: Bank --- # Manages multiple accounts class Bank: def __init__(self, name): self.name = name self.accounts = {} # Dictionary to store accounts: {account_number: account_object} def create_account(self, holder_name, is_savings=False): if is_savings: new_acc = SavingsAccount(holder_name) else: new_acc = BankAccount(holder_name) self.accounts[new_acc._account_number] = new_acc print(f"\nSuccess! Account created for {holder_name}.") print(f"Your Account Number is: {new_acc._account_number}") return new_acc._account_number def get_account(self, acc_num): # Basic validation to ensure account exists return self.accounts.get(acc_num, None) def transfer_money(self, sender_num, receiver_num, amount): sender = self.get_account(sender_num) receiver = self.get_account(receiver_num) if not sender or not receiver: print("Transfer failed: One or both accounts not found.") return if amount <= 0: print("Transfer failed: Amount must be positive.") return if sender.get_balance() >= amount: # Perform transfer sender.withdraw(amount) # Manually log transfer description to overwrite standard "Withdrawal" text if we wanted to be fancy, # but for this simulation, we just deposit on the other end. receiver.deposit(amount) print(f"Transfer of ${amount:.2f} from {sender_num} to {receiver_num} successful.") else: print("Transfer failed: Insufficient funds.") # --- 4. MAIN EXECUTION (User Interface) --- def main(): my_bank = Bank("OOP Python Bank") while True: print("\n==============================") print(f"Welcome to {my_bank.name}") print("==============================") print("1. Create Standard Account") print("2. Create Savings Account") print("3. Deposit Money") print("4. Withdraw Money") print("5. Check Balance / Info") print("6. Transfer Money") print("7. Apply for Interest (Savings Only)") print("8. Print Transaction History") print("9. Exit") choice = input("Enter your choice (1-9): ") if choice == '1': name = input("Enter Account Holder Name: ") my_bank.create_account(name, is_savings=False) elif choice == '2': name = input("Enter Account Holder Name: ") my_bank.create_account(name, is_savings=True) elif choice in ['3', '4', '5', '6', '7', '8']: acc_num = input("Enter your Account Number: ") account = my_bank.get_account(acc_num) if not account: print("Error: Account not found.") continue if choice == '3': # Deposit try: amt = float(input("Enter amount to deposit: ")) account.deposit(amt) except ValueError: print("Invalid input. Please enter a number.") elif choice == '4': # Withdraw try: amt = float(input("Enter amount to withdraw: ")) account.withdraw(amt) except ValueError: print("Invalid input. Please enter a number.") elif choice == '5': # Info print("\nAccount Details:") print(account.get_account_info()) elif choice == '6': # Transfer target_num = input("Enter Target Account Number: ") try: amt = float(input("Enter amount to transfer: ")) my_bank.transfer_money(acc_num, target_num, amt) except ValueError: print("Invalid input.") elif choice == '7': # Interest # Check if it is actually a savings account using isinstance if isinstance(account, SavingsAccount): account.apply_interest() else: print("Error: Interest can only be applied to Savings Accounts.") elif choice == '8': # History account.print_statement() elif choice == '9': print("Thank you for using the system. Goodbye!") break else: print("Invalid choice. Please try again.") if __name__ == "__main__": main()How to test this program:
- Run the script.
- Select 1 or 2 to create accounts. Copy the Account Number that is printed (e.g., 83921023).
- Select 3 to deposit some money into the account.
- Select 4 to withdraw money.
- (Optional) Create a second account and use option 6 to transfer money between them.
- If you created a Savings Account (Option 2), select 7 to see interest added automatically.
- Select 8 to see a full table of every action you took.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.