How to Use OOP in Python – with a Bank Account Example

Object-Oriented Programming (OOP) lets us model real-world things as code. In this tutorial, we’ll use a Bank Account to demonstrate how to use OOP concepts in Python.

Step 1: Define the Class

We’ll start by creating a simple BankAccount class with a few attributes.

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

Step 2: Add Methods

Now let’s add some basic functionality: deposit, withdraw, and check balance.

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        if amount > 0:
            self.balance += amount
            print(f"Deposited ${amount}. New balance: ${self.balance}")
        else:
            print("Deposit amount must be positive.")

    def withdraw(self, amount):
        if amount > self.balance:
            print("Insufficient funds.")
        else:
            self.balance -= amount
            print(f"Withdrew ${amount}. New balance: ${self.balance}")

    def display_balance(self):
        print(f"{self.owner}'s account balance: ${self.balance}")

Step 3: Create and Use an Object

We’ll start by creating a simple BankAccount class with a few attributes.

account1 = BankAccount("Alice", 100)

account1.display_balance()  # Alice's account balance: $100
account1.deposit(50)        # Deposited $50. New balance: $150
account1.withdraw(30)       # Withdrew $30. New balance: $120
account1.withdraw(200)      # Insufficient funds.

Step 4: Inheritance (Advanced Concept)

Let’s say we want a SavingsAccount that earns interest. We can extend the BankAccount class.

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

    def apply_interest(self):
        interest = self.balance * self.interest_rate
        self.balance += interest
        print(f"Interest applied: ${interest:.2f}. New balance: ${self.balance:.2f}")
savings = SavingsAccount("Bob", 1000)
savings.display_balance()    # Bob's account balance: $1000
savings.apply_interest()     # Interest applied: $20.00. New balance: $1020.00

Leave a Reply

Your email address will not be published. Required fields are marked *