Mini-Project: Bank Account Class
__init__, instance methods, encapsulated state, and tracking a list of events on a single object.Before you start
#What you'll build
BankAccount class with deposit, withdraw, balance, and a full transaction history. Then a transfer method that moves money between two accounts atomically — the first real "method that interacts with another object" you'll write.Sample interaction
>>> alice = BankAccount("Alice", 100)
>>> alice.deposit(50)
>>> alice.withdraw(30)
>>> alice.balance
120
>>> alice.history
['opened with 100', 'deposit 50', 'withdraw 30']
>>> bob = BankAccount("Bob", 0)
>>> alice.transfer(bob, 70)
>>> alice.balance, bob.balance
(50, 70)
#What you'll learn
After this lesson, you will be able to:
- Define a class with __init__ and instance attributes
- Add methods that read and update self
- Have one object call methods on another object
#Step 1: A class with an init
__init__ is the constructor — it runs when you do BankAccount(...).class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
alice = BankAccount("Alice", 100)
print(alice.owner) # Alice
print(alice.balance) # 100self is the instance being created. self.owner = owner stores the argument as an attribute on the instance. Every method you write on this class will receive self as its first argument.What does `BankAccount('Alice', 100)` create?
#Step 2: Deposit method
self as its first parameter — that's how it knows WHICH account to operate on.class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self.balance += amount
alice = BankAccount("Alice", 100)
alice.deposit(50)
print(alice.balance) # 150alice.deposit(50) is sugar for BankAccount.deposit(alice, 50). Python passes alice as self automatically.#Step 3: Withdraw with a check
Don't let a withdrawal take the balance below zero, and reject amounts that are zero or negative (a negative deposit would quietly act as a withdrawal). Return True if the withdrawal succeeded, False if it failed.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self.balance += amount
def withdraw(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
if amount > self.balance:
return False
self.balance -= amount
return True
alice = BankAccount("Alice", 100)
print(alice.withdraw(50)) # True
print(alice.withdraw(500)) # False (too big)
print(alice.balance) # 50ValueError otherwise), so callers can rely on that without checking themselves.Why return True/False from withdraw instead of just printing 'Insufficient funds'?
#Step 4: Transaction history
self.history = [] in __init__. Append a description string on every operation.class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
self.history = [f"opened with {balance}"]
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self.balance += amount
self.history.append(f"deposit {amount}")
def withdraw(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
if amount > self.balance:
self.history.append(f"FAILED withdraw {amount}")
return False
self.balance -= amount
self.history.append(f"withdraw {amount}")
return True
alice = BankAccount("Alice", 100)
alice.deposit(50)
alice.withdraw(30)
print(alice.history)
# ['opened with 100', 'deposit 50', 'withdraw 30']Even failed attempts are logged, which is exactly what real banks do for audit purposes.
#Step 5: Transfer between two accounts
transfer is the first method that uses ANOTHER instance. It calls withdraw on self, and if that succeeds, deposit on the other account.class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
self.history = [f"opened with {balance}"]
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self.balance += amount
self.history.append(f"deposit {amount}")
def withdraw(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
if amount > self.balance:
self.history.append(f"FAILED withdraw {amount}")
return False
self.balance -= amount
self.history.append(f"withdraw {amount}")
return True
def transfer(self, other, amount):
if other is self:
raise ValueError("cannot transfer to the same account")
if self.withdraw(amount):
other.deposit(amount)
self.history.append(f"transferred {amount} to {other.owner}")
other.history.append(f"received {amount} from {self.owner}")
return True
return False
alice = BankAccount("Alice", 100)
bob = BankAccount("Bob", 0)
alice.transfer(bob, 70)
print(alice.balance, bob.balance) # 30 70
print(bob.history)
# ['opened with 0', 'deposit 70', 'received 70 from Alice']transfer reuses withdraw and deposit rather than directly touching balances. That's encapsulation in action — the invariants stay safe and the logic stays in one place.#Now build it yourself
Full BankAccount with transfer and history
Build a `BankAccount` class with: `__init__(owner, balance=0)`, `deposit(amount)`, `withdraw(amount)` and `transfer(other, amount)` (both return True or False), and a `history` list that logs every operation (including failed withdrawals). Withdraw must refuse if balance < amount, and deposit and withdraw must raise `ValueError` for an amount of zero or less. Transfer must be all-or-nothing: if the withdraw fails, no deposit happens. Transferring to the same account must raise `ValueError`.
Alice balance: 100
Bob balance: 0
Alice transfers 30 to Bob
Alice balance: 70
Bob balance: 30
Bob tries to withdraw 500 -- success? False
Bob history: ['opened with 0', 'received 30 from Alice', 'FAILED withdraw 500']#Now make it your own
Try one of these variations:
- Interest. Add an
accrue_interest(rate)method that multiplies balance by(1 + rate). Log it in history. Apply it to a list of accounts in a single for loop. - Overdraft limit. Accept an
overdraft=0parameter. Withdraw is allowed as long as the resulting balance is>= -overdraft. Log overdraft usage separately. - Account subclasses. Create
SavingsAccount(BankAccount)that adds a monthly interest method, andCheckingAccount(BankAccount)that adds a transfer fee. Override or extend__init__as needed.
#What's next
-> bool and amount: float to the methods makes the class self-documenting and lets editors catch mistakes before you run the code. Then pytest lets you lock in the "balance never goes negative" promise with automated tests.