Appearance
D2 · Object-Oriented Programming (OOP)
Spec reference: Section D - Programming Languages
Key idea: Model programs as interacting objects that combine data (attributes) and behaviour (methods).
Object-Oriented Programming: Classes and Objects
Classes and objects
python
# Define the class (blueprint)
class Student:
def __init__(self, name, age, score):
self.name = name # attribute
self.age = age # attribute
self.score = score # attribute
def get_grade(self): # method
if self.score >= 70:
return "Distinction"
elif self.score >= 55:
return "Merit"
elif self.score >= 40:
return "Pass"
else:
return "Fail"
def display(self): # method
print(f"{self.name} (age {self.age}): {self.get_grade()}")
# Create objects (instances)
student1 = Student("Alice", 17, 82)
student2 = Student("Bob", 16, 55)
student1.display() # Alice (age 17): Distinction
student2.display() # Bob (age 16): Merit
print(student1.name) # Access attribute: AliceThe four pillars of OOP
1. Encapsulation
Encapsulation bundles data and methods together inside a class, and controls access to them. Internal details are hidden from outside code - only the methods you choose to expose are public.
python
class BankAccount:
def __init__(self, balance):
self.__balance = balance # __ makes it private
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount(500)
account.deposit(100)
print(account.get_balance()) # 600
# print(account.__balance) # Error - private!Why? Protects data from accidental or malicious changes. The account balance can only be changed through deposit() - not directly.
2. Inheritance
Inheritance allows a new class (child/subclass) to inherit attributes and methods from an existing class (parent/superclass). The child can add new features or override existing ones.
python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal): # Dog inherits from Animal
def speak(self): # override the parent's method
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
dog = Dog("Rex")
cat = Cat("Luna")
print(dog.name, dog.speak()) # Rex Woof!
print(cat.name, cat.speak()) # Luna Meow!Why? Promotes code reuse - don't rewrite shared behaviour. A Dog automatically has name from Animal without rewriting it.
3. Polymorphism
Polymorphism means the same method name can behave differently depending on which object calls it. From the example above, speak() behaves differently for a Dog vs a Cat.
python
animals = [Dog("Rex"), Cat("Luna"), Dog("Buddy")]
for animal in animals:
print(animal.name, animal.speak())
# Rex Woof!
# Luna Meow!
# Buddy Woof!Why? Simplifies code - you can treat different objects the same way and let each one behave correctly.
4. Abstraction (in OOP)
In OOP, abstraction means hiding complex implementation details behind a simple interface. Users of a class don't need to know how methods work internally.
python
# User just calls drive() - they don't need to know
# how the engine, gear system, or fuel injection works
car.drive()
car.brake()Class diagrams (UML)
Classes are often described visually using UML class diagrams:
┌─────────────────────┐
│ Student │
├─────────────────────┤
│ - name: String │ ← Attributes (- means private)
│ - age: Integer │
│ - score: Integer │
├─────────────────────┤
│ + __init__() │ ← Methods (+ means public)
│ + get_grade() │
│ + display() │
└─────────────────────┘Inheritance is shown with an arrow from child to parent:
Animal
▲
│
Dog CatOOP vs Procedural - when to use each
| OOP | Procedural |
|---|---|
| Complex systems with many entity types | Simpler scripts and utilities |
| Models real-world objects naturally | Linear, step-by-step processes |
| Long-lived, maintained software | Short programs |
| Team-based development | Solo or small projects |
| Examples: games, apps, banking systems | Examples: data processing scripts, calculators |
Test Yourself
Question 1 of 5
What is a class in OOP?