Classes and objectsclasses-bank-account
Lesson·difficulty 2/5·~15 min
Classes: bank account
Classes: bank account
A class bundles related state and behavior into one object. __init__
sets up each instance, self refers to that instance, and methods are
functions that act on it:
python
class Counter:
def __init__(self, start=0):
self.value = start # per-instance state
def bump(self): # a method
self.value += 1
c = Counter()
c.bump()
c.value # 1
Your task
Write a BankAccount class that tracks a balance and remembers every
transaction. It starts at a given balance and supports:
deposit(amount)— add to the balance.withdraw(amount)— subtract, but only if there are enough funds; if not, leave the balance unchanged.history()— return the list of successful transaction amounts in order (deposits positive, withdrawals negative).
python
acc = BankAccount(100)
acc.deposit(50) # balance 150
acc.withdraw(30) # balance 120
acc.withdraw(1000) # rejected — not enough funds
acc.balance # 120
acc.history() # [50, -30]
Hint: store self.balance in __init__ and keep a self.log list. In
withdraw, guard with if amount <= self.balance: before applying it.
Tests
- deposit then withdraw
- history order
- overdraft rejected
- overdraft not logged
- default balance zero (hidden)
- exact withdraw allowed (hidden)
Stuck? Ask for a spark
warming up
Loading editor…
$ Console output will appear here.