🏛️ Topic 08 · OOP
Object-Oriented Programming
Model real-world entities using classes and objects. Learn encapsulation, inheritance, and polymorphism in Python.
⏱ ~60 min
🟡 Intermediate
🏗️ Design
Classes & Objects
A class is a blueprint; an object is a live instance of that blueprint with its own data.
class_basics.py
class Dog:
"""A simple dog class."""
def __init__(self, name, breed):
self.name = name # instance attribute
self.breed = breed
def bark(self):
return f"{self.name} says: Woof!"
def __repr__(self):
return f"Dog(name={self.name!r})"
rex = Dog("Rex", "Labrador")
print(rex.bark()) # Rex says: Woof!
print(rex) # Dog(name='Rex')
Inheritance
A subclass inherits all methods and attributes from its parent and can override or extend them.
inheritance.py
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError
class Cat(Animal): # inherits Animal
def speak(self): # overrides
return f"{self.name}: Meow"
class Duck(Animal):
def speak(self):
return f"{self.name}: Quack"
# Polymorphism — same call, different behaviour
for a in [Cat("Kitty"), Duck("Donald")]:
print(a.speak())
Class vs Instance Attributes
attributes.py
class Counter:
count = 0 # class attribute (shared by all)
def __init__(self):
Counter.count += 1
self.id = Counter.count # instance attribute
a = Counter()
b = Counter()
print(Counter.count) # 2
print(a.id, b.id) # 1 2
Properties & Encapsulation
Use @property to create managed attributes with getters and optional setters.
properties.py
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def fahrenheit(self):
return self._celsius * 9/5 + 32
@fahrenheit.setter
def fahrenheit(self, value):
self._celsius = (value - 32) * 5/9
t = Temperature(100)
print(t.fahrenheit) # 212.0
🔒 Private naming convention Prefix with _name for "internal use" or __name for name-mangled private access. Python has no enforced private members.