Unit: Unit 7: Introduction to Classes • Interactive Practice
Interactive Python programming tutorial and practice in your 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)