Unit 5 · Advanced Topics
Introduction to Object-Oriented Programming
Learn the fundamentals of Object-Oriented Programming (OOP) in Python — the four pillars, procedural vs OOP comparison, real-world analogies, and why OOP is essential for modern software development.
Table of Contents
What is Object-Oriented Programming?
University Definition
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects rather than functions and logic. An object is a data field that has unique attributes and behavior. OOP binds data and the methods that operate on that data into a single unit, promoting modularity, reusability, and scalability.
In OOP, programs are structured as a collection of objects that interact with each other. Each object is an instance of a class, which defines the properties (attributes) and behaviors (methods) that its objects will have.
OOP Key Concepts: ================== Object = Instance of a Class Class = Blueprint / Template Method = Function inside a class Attribute = Variable inside a class Real World: Car (Class) -> My Car (Object) Student (Class) -> Rahul (Object) Phone (Class) -> iPhone 15 (Object)
Procedural vs Object-Oriented Programming
# PROCEDURAL APPROACH - Step by step instructions
def create_student(name, age, grade):
return {"name": name, "age": age, "grade": grade}
def display_student(student):
print(f"Name: {student['name']}, Age: {student['age']}, Grade: {student['grade']}")
def is_passing(student):
return student["grade"] in ["A", "B", "C"]
# Data and functions are SEPARATE
student = create_student("Rahul", 20, "A")
display_student(student)
print("Passing:", is_passing(student))
# OOP APPROACH - Data and functions TOGETHER
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
def display(self):
print(f"Name: {self.name}, Age: {self.age}, Grade: {self.grade}")
def is_passing(self):
return self.grade in ["A", "B", "C"]
# Data and behavior are BUNDLED together
student = Student("Rahul", 20, "A")
student.display()
print("Passing:", student.is_passing())
| Feature | Procedural | Object-Oriented |
|---|---|---|
| Focus | Functions/Procedures | Objects/Classes |
| Data | Passed between functions | Encapsulated in objects |
| Reusability | Limited (copy-paste) | High (inheritance, polymorphism) |
| Security | Data is exposed | Data hiding (encapsulation) |
| Scalability | Hard for large projects | Ideal for large projects |
| Example | C, Fortran, BASIC | Python, Java, C++ |
Four Pillars of OOP
Object-Oriented Programming is built on four fundamental concepts:
The Four Pillars of OOP
========================
1. Encapsulation - Bundling data and methods together
2. Inheritance - Creating new classes from existing ones
3. Polymorphism - Same interface, different behavior
4. Abstraction - Hiding complexity, showing essentials
1. Encapsulation
Encapsulation is the bundling of data (attributes) and methods that operate on that data into a single unit (class). It also restricts direct access to some components, providing data hiding.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private - hidden from outside
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self): # Controlled access
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # 1500
# print(account.__balance) # AttributeError - hidden!
2. Inheritance
Inheritance allows a new class (child/derived) to inherit attributes and methods from an existing class (parent/base). It promotes code reuse and establishes a hierarchy.
class Animal: # Parent class
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Dog(Animal): # Child class inherits from Animal
def speak(self):
print(f"{self.name} barks")
class Cat(Animal):
def speak(self):
print(f"{self.name} meows")
dog = Dog("Buddy")
cat = Cat("Whiskers")
dog.speak() # Buddy barks (overridden)
cat.speak() # Whiskers meows (overridden)
3. Polymorphism
Polymorphism (meaning "many forms") allows objects of different classes to be treated as objects of a common parent class. The same method name can behave differently depending on the object calling it.
# Polymorphism in action
class Circle:
def area(self):
return 3.14 * self.radius ** 2
class Rectangle:
def area(self):
return self.length * self.width
class Triangle:
def area(self):
return 0.5 * self.base * self.height
# Same method name, different behavior
shapes = [Circle(), Rectangle(), Triangle()]
for shape in shapes:
print(shape.area()) # Each calls its own area()
4. Abstraction
Abstraction hides the complex implementation details and shows only the essential features of the object. Users interact with a simple interface while the complexity is handled internally.
from abc import ABC, abstractmethod
class Vehicle(ABC): # Abstract class
@abstractmethod
def start(self): # Abstract method - no implementation
pass
class Car(Vehicle):
def start(self): # Must implement abstract method
print("Turning the key... Engine starts!")
class Bike(Vehicle):
def start(self):
print("Pressing the button... Bike starts!")
car = Car()
bike = Bike()
car.start() # Turning the key... Engine starts!
bike.start() # Pressing the button... Bike starts!
Real-World Analogy
Real World Python OOP --------- ---------- Blueprint -> Class House built -> Object Room design -> Method Room color/size -> Attribute Building houses -> Instantiation Example: Car Blueprint = Class Car My Car = Object (instance) Accelerate() = Method Color, Speed = Attributes
class Car:
"""Blueprint for creating car objects"""
def __init__(self, brand, color, speed):
self.brand = brand # Attribute
self.color = color # Attribute
self.speed = speed # Attribute
def accelerate(self): # Method
self.speed += 10
print(f"{self.brand} speed: {self.speed} km/h")
def brake(self): # Method
self.speed -= 10
print(f"{self.brand} speed: {self.speed} km/h")
# Creating objects from the blueprint
car1 = Car("Toyota", "Red", 60) # Object 1
car2 = Car("Honda", "Blue", 80) # Object 2
car1.accelerate() # Toyota speed: 70 km/h
car2.brake() # Honda speed: 70 km/h
print(f"Car1: {car1.brand} {car1.color}")
print(f"Car2: {car2.brand} {car2.color}")
Advantages of OOP
Advantages of OOP: ================== 1. Modularity - Code is organized into classes 2. Reusability - Inheritance allows code reuse 3. Data Hiding - Encapsulation protects data 4. Flexibility - Polymorphism allows interchangeable use 5. Scalability - Easy to extend and maintain 6. Debugging - Easier to locate and fix errors 7. Team Work - Different classes can be developed by different developers
Key Points
OOP organizes code around objects that combine data and behavior.
A class is a blueprint; an object is an instance of that class.
The four pillars are: Encapsulation, Inheritance, Polymorphism, Abstraction.
OOP promotes code reuse through inheritance and data security through encapsulation.
Python supports OOP along with procedural and functional programming.
OOP is ideal for large, complex, and collaborative software projects.
Common Mistakes to Avoid
- Confusing a class (blueprint) with an object (instance).
- Using OOP for very small programs where procedural is simpler.
- Creating too many classes for trivial functionality.
- Not understanding that Python supports multiple paradigms — choose what fits.
- Assuming OOP always means better performance — it prioritizes design over speed.
Practice Questions
- Explain the difference between procedural and OOP with a real-life example.
- Give a real-world analogy for each of the four pillars of OOP.
- Write a short example demonstrating inheritance with a parent Animal class and child Dog class.
- Explain why data hiding (encapsulation) is important in banking applications.
Summary
Object-Oriented Programming is a powerful paradigm that structures programs around objects combining data and behavior. Python supports OOP through its class system. The four pillars — Encapsulation, Inheritance, Polymorphism, and Abstraction — enable developers to write modular, reusable, and scalable code. OOP is particularly valuable for large projects requiring maintainability and team collaboration.