7.2.2 Understanding self and Instance Methods

Unit: Unit 7: Introduction to Classes • Interactive Practice

Quick Answer & Summary:

Interactive Python programming tutorial and practice in your browser.

Interactive Challenge (Run Live in Browser):

# Define a BankAccount class with state-mutating instance methods
class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    # Instance method reading and writing self
    def deposit(self, amount):
        self.balance += amount
        print(f"{self.owner} deposited ${amount}. New balance: ${self.balance}")

    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
            print(f"{self.owner} withdrew ${amount}. Remaining balance: ${self.balance}")
        else:
            print(f"Withdrawal denied: Insufficient funds for {self.owner}.")

# Open an account and perform transactions
acct = BankAccount("Jordan", 500)
acct.deposit(200)
acct.withdraw(150)
acct.withdraw(700)
Open in Live Interactive Python Sandbox →