A bank account is a real-world entity that has attributes such as an account holder’s name, balance, and account number. It also supports actions like depositing and withdrawing money.
In this example, we will create a BankAccount
class in Python that includes:
✅ Attributes: Account holder name and balance
✅ Methods: Deposit, withdraw, and display balance
✅ Encapsulation: Ensuring safe balance management
This example demonstrates object-oriented programming (OOP) by encapsulating data (balance, account holder) and behavior (transactions) in a structured way.
class BankAccount:
"""Class to simulate a bank account with deposit and withdrawal functionality."""
def __init__(self, account_holder, balance=0.0):
"""Constructor to initialize account holder and balance."""
self.account_holder = account_holder
self.balance = balance
def deposit(self, amount):
"""Method to deposit money into the account."""
if amount > 0:
self.balance += amount
print(f"Deposited ${amount:.2f}. New balance: ${self.balance:.2f}")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
"""Method to withdraw money from the account."""
if 0 < amount <= self.balance:
self.balance -= amount
print(f"Withdrew ${amount:.2f}. New balance: ${self.balance:.2f}")
elif amount > self.balance:
print("Insufficient funds.")
else:
print("Withdrawal amount must be positive.")
def display_balance(self):
"""Method to display the current balance."""
print(f"Account Holder: {self.account_holder}, Balance: ${self.balance:.2f}")
# Creating a bank account for John Doe with an initial balance of $1000
account = BankAccount("John Doe", 1000.0)
# Performing transactions
account.display_balance()
account.deposit(500)
account.withdraw(300)
account.withdraw(1500) # Should trigger "Insufficient funds"
Account Holder: John Doe, Balance: $1000.00
Deposited $500.00. New balance: $1500.00
Withdrew $300.00. New balance: $1200.00
Insufficient funds.
BankAccount
class
__init__
method that initializes the account holder and balance.deposit()
method
withdraw()
method
display_balance()
method
BankAccount
object is created with an initial balance.This example demonstrates OOP principles like encapsulation and data management, making the bank account secure, reusable, and scalable! 🚀