Python BankAccount Class Example
class / methods Topic 09 Practice

Manage state with multiple methods

Create a BankAccount class with deposit() and withdraw() methods that modify the account balance.

Picture this: deposit adds to balance

The object remembers balance. deposit(amount) updates it.

balanceinside object
→
deposit(n)add n
→
new balancestored

Multiple methods in a class

A class can have many methods that work together. Each method modifies or queries the object's state (stored in self).

Real-world use

Banks model accounts as objects with balance, deposit(), withdraw(), and transfer() methods. Games use Character objects with move(), attack(), heal(). UI uses Button objects with click(), hide(), show().

UML Class Diagram

BankAccount
- balance: int
+ __init__()
+ deposit(amt)
+ withdraw(amt)

Transaction State Diagram

Initial
balance=0
deposit(100)
balance=100
withdraw(30)
balance=70

BankAccount class

1class BankAccount:
2def __init__(self):
3self.balance = 0
4def deposit(self, amt):
5self.balance += amt
6def withdraw(self, amt):
7self.balance -= amt

account.deposit(100)

Press "Run one step" to see balance update

Sequence example

1account = BankAccount()
2account.deposit(100) # balance = 100
3account.deposit(50) # balance = 150
4account.withdraw(30) # balance = 120