OOP · Python example
Model a bank account with a class, methods, and simple validation.
Classes combine data and behaviour. This small account object stores an owner and balance, and exposes methods for safe changes.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
return False
self.balance -= amount
return True
def __str__(self):
return f"{self.owner}: ${self.balance:.2f}"
account = BankAccount("Ada", 120)
print(account)
print("Withdrawal succeeded:", account.withdraw(50))
print(account)
print("Overdraft rejected:", not account.withdraw(1000))
print(account)