Classes & Objects
Object-Oriented Programming (OOP) is a paradigm where code is organized around "objects" rather than actions. An object contains both data (attributes) and code (methods). This lesson introduces the foundation of OOP: Classes and Objects.
Learning Objectives
- 11.4.1.1 Create classes and instances of classes
- 11.4.1.3 Use special method
__init__to set default properties - 11.4.1.2 Develop methods for the class
Conceptual Anchor
The Blueprint Analogy
Think of a Class as a blueprint for a house. It describes what
the house should have (walls, windows) and do (open door).
An Object (or Instance) is the actual house built from that
blueprint. You can build unlimited houses from one blueprint, and each house can have different
colors or furniture, but they all follow the same structure.
Rules & Theory
Defining a Class (11.4.1.1)
class Car:
pass # Empty class
# Creating instances (Objects)
my_car = Car()
your_car = Car()The
__init__ Method (11.4.1.3)
The __init__ method (constructor) runs automatically when you create a new object. It
initializes the object's attributes.
class Car:
def __init__(self, brand, model):
self.brand = brand # Attribute
self.model = model # Attribute
# Creating objects with data
c1 = Car("Toyota", "Camry")
c2 = Car("BMW", "X5")
print(c1.brand) # Toyota
print(c2.brand) # BMWMethods (11.4.1.2)
Methods are functions defined inside a class that define the behavior of the object.
The first parameter must always be self.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
self.speed = 0
def drive(self):
self.speed += 10
print(f"{self.brand} is driving at {self.speed} km/h")
def stop(self):
self.speed = 0
print(f"{self.brand} stopped.")
my_car = Car("Tesla", "Model S")
my_car.drive() # Tesla is driving at 10 km/h
my_car.drive() # Tesla is driving at 20 km/h
my_car.stop() # Tesla stopped. What is self?
self is a reference to the current object being used. When you call
my_car.drive(), Python automatically passes my_car as the
self argument.
Worked Examples
1 Student Class
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def promote(self):
self.grade += 1
print(f"{self.name} is now in Grade {self.grade}")
ali = Student("Ali", 10)
print(ali.grade) # 10
ali.promote() # Ali is now in Grade 112 Bank Account
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"Deposited {amount}. New balance: {self.balance}")
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
print(f"Withdrew {amount}. New balance: {self.balance}")
else:
print("Insufficient funds!")
acct = BankAccount("Dana", 1000)
acct.deposit(500) # 1500
acct.withdraw(2000) # Insufficient funds!Pitfalls & Common Errors
Forgetting self
Defining a method as def drive(): instead of def drive(self): causes a
TypeError when called.
__init__ Underscores
It is a double underscore on both sides! __init__, not _init_.
Graded Tasks
What is the difference between a class and an object? What is self?
Why do we need the __init__ method? What happens if we don't define it?
Create a class Rectangle with attributes length and width, and methods
area() and perimeter().
Design a Book class with title, author, and page count. Add a method
read(pages) that tracks current page progress.