Table of Contents
A Simple “Bank Account” Class
Let’s build a small but realistic example: a bank account.
We’ll use:
- A class
- Attributes (data)
- Methods (actions)
- The
__init__method - Simple encapsulation (with a “private” attribute)
- Multiple objects of the same class
class BankAccount:
def __init__(self, owner, balance=0):
# "private" attribute by convention (single underscore)
self._owner = owner
self._balance = balance
def deposit(self, amount):
if amount <= 0:
print("Deposit amount must be positive.")
return
self._balance += amount
print(f"Deposited {amount}. New balance: {self._balance}")
def withdraw(self, amount):
if amount <= 0:
print("Withdrawal amount must be positive.")
return
if amount > self._balance:
print("Insufficient funds.")
return
self._balance -= amount
print(f"Withdrew {amount}. New balance: {self._balance}")
def get_balance(self):
return self._balance
def get_owner(self):
return self._owner
# Using the class
account1 = BankAccount("Alice", 100)
account2 = BankAccount("Bob") # starts with default balance 0
account1.deposit(50)
account1.withdraw(30)
print("Alice's final balance:", account1.get_balance())
account2.deposit(200)
print("Bob's balance:", account2.get_balance())Things to notice (without re‑explaining the theory):
BankAccountis the blueprint.account1andaccount2are different objects with their own data.- Methods like
depositandwithdrawuse and change the object’s state. - The balance is only changed through methods (encapsulation style).
You can extend this yourself with a transfer_to(other_account, amount) method that withdraws from one account and deposits into the other.
A “To-Do Task” Class
Next, a very simple object you might use in a to-do list app.
class Task:
def __init__(self, title, priority=3):
self.title = title
self.priority = priority # 1 = high, 5 = low
self.completed = False
def mark_completed(self):
self.completed = True
def mark_pending(self):
self.completed = False
def __str__(self):
status = "✓" if self.completed else "✗"
return f"[{status}] ({self.priority}) {self.title}"
# Creating and using tasks
task1 = Task("Buy groceries", priority=2)
task2 = Task("Finish Python homework", priority=1)
print(task1)
print(task2)
task1.mark_completed()
print("After completing task1:")
print(task1)Key ideas shown here:
- Objects can hold several pieces of related data (
title,priority,completed). - Methods change the state (
mark_completed,mark_pending). __str__controls how the object is shown when youprintit.
A “Rectangle” Class with Methods
Now a small example that uses a bit of math: area and perimeter.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
def is_square(self):
return self.width == self.height
# Using the Rectangle class
r1 = Rectangle(4, 5)
r2 = Rectangle(3, 3)
print("r1 area:", r1.area())
print("r1 perimeter:", r1.perimeter())
print("r1 is square?", r1.is_square())
print("r2 area:", r2.area())
print("r2 is square?", r2.is_square())This example shows:
- Objects can compute values from their attributes.
- Methods like
areaandperimeterdon’t change the object; they just return information. - The same class can represent different specific rectangles (different widths and heights).
A Simple Inheritance Example: Animals
Let’s combine a base class and child classes that inherit from it.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
# Default / generic behavior
return "<silent>"
def info(self):
return f"I am an animal and my name is {self.name}."
class Dog(Animal):
def speak(self):
return "Woof!"
def fetch(self):
return f"{self.name} is fetching a ball."
class Cat(Animal):
def speak(self):
return "Meow!"
def scratch(self):
return f"{self.name} is scratching the sofa..."
# Using the classes
dog = Dog("Buddy")
cat = Cat("Luna")
print(dog.info()) # inherited from Animal
print("Dog says:", dog.speak()) # overridden in Dog
print(dog.fetch()) # only in Dog
print(cat.info()) # inherited from Animal
print("Cat says:", cat.speak()) # overridden in Cat
print(cat.scratch()) # only in CatWhat this demonstrates:
DogandCatreuse code fromAnimal.- They customize behavior by redefining
speak. - Each subclass can add extra methods (
fetch,scratch) specific to that type.
A Tiny “Shopping Cart” Example
Here we combine multiple objects that work together: products and a shopping cart.
class Product:
def __init__(self, name, price):
self.name = name
self.price = price # assume a float or int
def __str__(self):
return f"{self.name} (${self.price})"
class ShoppingCart:
def __init__(self):
self.items = [] # list of Product objects
def add_item(self, product):
self.items.append(product)
print(f"Added {product.name} to the cart.")
def total_price(self):
total = 0
for product in self.items:
total += product.price
return total
def show_items(self):
if not self.items:
print("Your cart is empty.")
return
print("Items in your cart:")
for product in self.items:
print(" -", product)
# Using the classes together
p1 = Product("Book", 12.99)
p2 = Product("Headphones", 39.90)
p3 = Product("Coffee mug", 7.50)
cart = ShoppingCart()
cart.add_item(p1)
cart.add_item(p2)
cart.add_item(p3)
cart.show_items()
print("Total price:", cart.total_price())This shows:
- One class (
ShoppingCart) containing objects of another class (Product). - Methods operating over a collection of objects.
- A small “system” formed from multiple classes.
Practice Ideas
To solidify these concepts, try these small variations:
- BankAccount
- Add a
show_ownermethod that prints the owner and current balance. - Add a simple
transfer_to(other_account, amount)method. - Task
- Add a
due_dateattribute (as a string to keep it simple). - Add a method
is_urgent()that returnsTruefor high-priority tasks. - Rectangle
- Add a method
resize(new_width, new_height)that changes the dimensions. - Add a method
scale(factor)that multiplieswidthandheightbyfactor. - Animal
- Add another subclass (e.g.
Bird) with its ownspeakand a new method likefly. - ShoppingCart
- Add a method
remove_item(product_name). - Add a simple discount (e.g. 10% off if total is above a certain amount).
In the next chapters and projects, you’ll combine these ideas into larger, more useful programs.