Home Week 7 7.1 Project: Bank System
WEEK 7 LESSON 1 OF 3 PROJECT

Project: Bank System

Build a complete banking system using everything you have learned about OOP.

Project Overview

In this project, you will build a fully functional banking system that supports multiple account types. This is a real-world application of OOP that uses all four pillars: Encapsulation, Inheritance, Polymorphism, and Abstraction.

Create bank accounts
Deposit and withdraw money
Transfer between accounts
View account statements
Calculate interest
Savings and Checking types

OOP Concepts Used

Encapsulation

Private balance attribute prevents direct modification. All changes go through controlled methods like deposit() and withdraw().

Inheritance

SavingsAccount and CheckingAccount inherit from a shared BankAccount base class.

Polymorphism

Each account type calculates interest differently using the same method name.

Abstraction

The base BankAccount class is abstract -- you cannot create a generic account, only specific types.

Step 1: The Base Account Class

We start by creating an abstract base class that defines what every bank account must have. Notice that calculate_interest is abstract -- each account type will implement it differently.

from abc import ABC, abstractmethod

class BankAccount(ABC):
    _next_id = 1000

    def __init__(self, owner, balance=0):
        self._owner = owner
        self._balance = balance
        self._account_id = BankAccount._next_id
        BankAccount._next_id += 1
        self._transactions = []

    @property
    def balance(self):
        return self._balance

    @property
    def owner(self):
        return self._owner

    def deposit(self, amount):
        if amount > 0:
            self._balance += amount
            self._transactions.append(f"Deposit: +${amount:.2f}")
            return True
        return False

    def withdraw(self, amount):
        if 0 < amount <= self._balance:
            self._balance -= amount
            self._transactions.append(f"Withdrawal: -${amount:.2f}")
            return True
        return False

    @abstractmethod
    def calculate_interest(self):
        pass

    def get_statement(self):
        print(f"\n--- Account #{self._account_id} ---")
        print(f"Owner: {self._owner}")
        print(f"Balance: ${self._balance:.2f}")
        for t in self._transactions[-5:]:
            print(f"  {t}")

    def __str__(self):
        return f"Account #{self._account_id} ({self._owner}): ${self._balance:.2f}"

Why abstract? We use ABC and @abstractmethod because a generic "bank account" does not make sense on its own -- it must be a savings or checking account. This prevents someone from writing BankAccount("Alice") directly.

Breaking Down the Base Class

_next_id -- Class Variable

This is shared across all accounts. Every time a new account is created, the ID increments. This ensures every account gets a unique number.

_balance -- Encapsulation

The underscore prefix marks this as protected. You can only read the balance through the @property, and modify it through deposit() or withdraw().

_transactions -- History Tracking

A list that records every deposit and withdrawal. The get_statement() method shows the last 5 transactions.

Step 2: Savings Account

A savings account earns higher interest. It inherits everything from BankAccount and adds its own interest rate. Notice how short this class is -- inheritance lets us reuse all the base class code.

class SavingsAccount(BankAccount):
    def __init__(self, owner, balance=0, interest_rate=0.05):
        super().__init__(owner, balance)
        self._interest_rate = interest_rate

    def calculate_interest(self):
        interest = self._balance * self._interest_rate
        self._balance += interest
        self._transactions.append(f"Interest: +${interest:.2f}")
        return interest

Inheritance in action: SavingsAccount gets deposit(), withdraw(), get_statement(), and __str__() for free from the parent class. We only need to write what is different.

Step 3: Checking Account

A checking account has lower interest but allows overdraft -- you can withdraw more than your balance, up to a limit. This demonstrates method overriding: we replace the parent's withdraw() with our own version.

class CheckingAccount(BankAccount):
    def __init__(self, owner, balance=0, overdraft_limit=500):
        super().__init__(owner, balance)
        self._overdraft_limit = overdraft_limit

    def withdraw(self, amount):
        if 0 < amount <= (self._balance + self._overdraft_limit):
            self._balance -= amount
            self._transactions.append(f"Withdrawal: -${amount:.2f}")
            return True
        return False

    def calculate_interest(self):
        interest = self._balance * 0.01
        self._balance += interest
        self._transactions.append(f"Interest: +${interest:.2f}")
        return interest

Polymorphism: Both SavingsAccount and CheckingAccount have a calculate_interest() method, but each one works differently. Savings uses 5% interest while Checking uses 1%. Same method name, different behavior.

Step 4: The Bank Class

The Bank class ties everything together. It manages a collection of accounts and provides high-level operations like creating accounts and transferring money.

class Bank:
    def __init__(self, name):
        self.name = name
        self._accounts = {}

    def create_savings(self, owner, balance=0):
        acc = SavingsAccount(owner, balance)
        self._accounts[acc._account_id] = acc
        return acc

    def create_checking(self, owner, balance=0):
        acc = CheckingAccount(owner, balance)
        self._accounts[acc._account_id] = acc
        return acc

    def transfer(self, from_id, to_id, amount):
        from_acc = self._accounts.get(from_id)
        to_acc = self._accounts.get(to_id)
        if from_acc and to_acc and from_acc.withdraw(amount):
            to_acc.deposit(amount)
            return True
        return False

    def get_account(self, account_id):
        return self._accounts.get(account_id)

    def apply_interest_all(self):
        for acc in self._accounts.values():
            acc.calculate_interest()

    def __str__(self):
        return f"{self.name} - {len(self._accounts)} accounts"

Design pattern: The Bank class uses a dictionary to store accounts, with the account ID as the key. This makes it fast to look up any account by its ID when doing transfers.

Step 5: Using the System

Here is a complete demo that creates a bank, opens accounts, makes transactions, and prints statements. Try running this code yourself!

# Create the bank
bank = Bank("Python National Bank")

# Open accounts
alice_savings = bank.create_savings("Alice", 1000)
bob_checking = bank.create_checking("Bob", 500)

print(alice_savings)   # Account #1000 (Alice): $1000.00
print(bob_checking)    # Account #1001 (Bob): $500.00

# Make transactions
alice_savings.deposit(500)
alice_savings.withdraw(200)
bob_checking.deposit(300)

# Transfer money: Alice -> Bob
bank.transfer(alice_savings._account_id, bob_checking._account_id, 150)

# Apply interest to all accounts
bank.apply_interest_all()

# View statements
alice_savings.get_statement()
bob_checking.get_statement()

Expected Output:

Account #1000 (Alice): $1000.00
Account #1001 (Bob): $500.00

--- Account #1000 ---
Owner: Alice
Balance: $1207.50
  Deposit: +$500.00
  Withdrawal: -$200.00
  Withdrawal: -$150.00
  Interest: +$57.50

--- Account #1001 ---
Owner: Bob
Balance: $858.50
  Deposit: +$300.00
  Deposit: +$150.00
  Interest: +$8.50

Concepts Recap: Where Each Pillar Appears

Encapsulation

_balance is private. You cannot do account._balance = 999999 to cheat. All modifications go through deposit() and withdraw() which validate the amount first.

Inheritance

SavingsAccount and CheckingAccount both inherit from BankAccount. They get deposit, withdraw, and statement features automatically.

Polymorphism

calculate_interest() behaves differently for each account type. withdraw() also works differently for CheckingAccount (allows overdraft).

Abstraction

BankAccount is abstract. You cannot create a plain BankAccount -- you must choose Savings or Checking. The @abstractmethod decorator enforces this.

Extension Exercises

Exercise 1: Withdrawal Limit

Add a daily withdrawal limit to SavingsAccount. Track how much has been withdrawn today, and reject withdrawals that exceed the limit. You will need a new attribute and modifications to the withdraw method.

Exercise 2: Account Fees

Add a monthly maintenance fee to CheckingAccount. Create a method apply_monthly_fee() that deducts a fixed amount and records it in the transaction history.

Exercise 3: Joint Accounts

Create a JointAccount class that has two owners instead of one. Override __str__() and get_statement() to display both owner names.

Summary

  • You built a complete banking system with multiple account types.
  • Encapsulation protects the balance from unauthorized changes.
  • Inheritance lets Savings and Checking reuse common account logic.
  • Polymorphism allows different interest calculations under the same interface.
  • Abstraction prevents creating incomplete generic accounts.
  • Next: Build a Student Management System using similar patterns.