SAMANTUS Python for Data Analytics — Complete Training Manual MODULE 11
← Back to Course Index

Object-Oriented Programming


On This Page

Module 11: Object-Oriented Programming


11.1  Classes & Objects

A class is a blueprint for creating objects. An object is a real instance created from that blueprint, with its own data. Think of a class as a 'course template' and each enrolled student as an individual object created from it.

► Defining a Class and Creating Objects
class Student:
    def __init__(self, name, course):
        self.name = name
        self.course = course

    def display(self):
        print(f"{self.name} is enrolled in {self.course}")

s1 = Student("Priya", "SEO")       # object 1
s2 = Student("Rahul", "Google Ads") # object 2
s1.display()
s2.display()
Output
Priya is enrolled in SEO
Rahul is enrolled in Google Ads

11.2  Constructors (__init__)

The __init__ method is a special function called a constructor — it runs automatically whenever a new object is created, used to set up the object's initial data.

ℹ Note
self refers to the specific object being worked on. It must be the first parameter of every method inside a class, though Python passes it automatically.

11.3  Encapsulation

Encapsulation means bundling data and the methods that operate on it together, while restricting direct access to some of an object's internal details — usually done by prefixing attributes with an underscore.

► Encapsulation Example
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance    # private attribute

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance

account = BankAccount(1000)
account.deposit(500)
print(account.get_balance())
# print(account.__balance)   # This would cause an ERROR - private attribute
Output
1500
✓ Real-World Use Case
Encapsulation protects sensitive data (like account balances or passwords) from being changed directly and carelessly from outside the class.

11.4  Inheritance

Inheritance allows one class (the child) to reuse the attributes and methods of another class (the parent), avoiding repeated code and modeling real-world 'is-a' relationships.

... ... Course (parent class) name duration fee SEOCourse (child) + keyword_tools AdsCourse (child) + ad_platforms
Figure — Inheritance: shared parent class attributes reused by child classes.

Figure 11.1 — SEOCourse and AdsCourse both inherit shared attributes from the parent Course class, while adding their own specific attributes.

► Inheritance in Code
class Course:
    def __init__(self, name, fee):
        self.name = name
        self.fee = fee

    def details(self):
        print(f"{self.name} costs Rs.{self.fee}")

class SEOCourse(Course):          # inherits from Course
    def __init__(self, name, fee, tools):
        super().__init__(name, fee)   # call parent constructor
        self.tools = tools

seo = SEOCourse("Advanced SEO", 12000, "Ahrefs, SEMrush")
seo.details()
print("Tools covered:", seo.tools)
Output
Advanced SEO costs Rs.12000
Tools covered: Ahrefs, SEMrush

11.5  Polymorphism

Polymorphism means the same method name can behave differently depending on the object calling it — 'many forms' of the same action.

► Polymorphism Example
class SEOCourse:
    def teach(self):
        print("Teaching keyword research and backlinks")

class AdsCourse:
    def teach(self):
        print("Teaching campaign structure and bidding")

courses = [SEOCourse(), AdsCourse()]
for c in courses:
    c.teach()    # same method name, different behavior
Output
Teaching keyword research and backlinks
Teaching campaign structure and bidding

11.6  Abstraction

Abstraction means hiding complex implementation details and showing only the essential features to the user — like a car's steering wheel hides the complex mechanics underneath.

► Simple Abstraction Example
class PaymentProcessor:
    def process_payment(self, amount):
        self.__validate(amount)     # hidden internal step
        self.__deduct_fee(amount)   # hidden internal step
        print(f"Payment of Rs.{amount} processed successfully!")

    def __validate(self, amount):
        pass   # complex validation logic hidden from the user

    def __deduct_fee(self, amount):
        pass   # complex fee logic hidden from the user

payment = PaymentProcessor()
payment.process_payment(5000)   # user only sees this simple call
Output
Payment of Rs.5000 processed successfully!

11.7  Mini Project — Student Management OOP

► student_management.py
class Student:
    def __init__(self, name, course, fee):
        self.name = name
        self.course = course
        self.__fee = fee   # encapsulated

    def apply_discount(self, percent):
        self.__fee -= self.__fee * percent / 100

    def summary(self):
        print(f"{self.name} | {self.course} | Rs.{self.__fee:.2f}")

students = [
    Student("Priya", "SEO", 12000),
    Student("Rahul", "Google Ads", 15000),
]

for s in students:
    s.apply_discount(10)
    s.summary()
Output
Priya | SEO | Rs.10800.00
Rahul | Google Ads | Rs.13500.00

11.8  Practical Exercises

Basic (5 Questions)

1. Create a class Course with name and fee attributes, then create 2 objects from it.

2. Add a method display() to the Course class that prints its details.

3. Create a class Student with a constructor that sets name and age.

4. Create a class with one private attribute and a method to safely access it.

5. Create 3 objects from the same class and print each one's details in a loop.

Intermediate (5 Questions)

1. Create a parent class Course and a child class OnlineCourse that adds a 'platform' attribute using inheritance.

2. Demonstrate polymorphism using 2 classes that both have a method called teach() with different behavior.

3. Create a class BankAccount with private balance, and methods to deposit, withdraw, and check balance safely.

4. Use super() to call a parent class's constructor from a child class.

5. Create an abstraction example where a class hides 2 internal helper methods and exposes only 1 public method.

Advanced (5 Questions)

1. Build a complete 'Course Management System' using a parent class Course and 2 child classes (e.g. SEOCourse, AdsCourse) with inheritance and polymorphism.

2. Create a class hierarchy: Person → Student → OnlineStudent, with each adding new attributes.

3. Build an encapsulated 'Fee Wallet' class where balance can only be modified through deposit() and deduct() methods, with validation.

4. Create 3 classes that all implement a common method calculate_fee() differently, and call it polymorphically in a loop.

5. Design (on paper first, then in code) a simple OOP model for a 'Library Management System' with Book and Member classes.

11.9  Module Quiz (MCQs)

Q1. What is a class?

Q2. Which method acts as a constructor in Python?

Q3. What does encapsulation help achieve?

Q4. What keyword is used to call a parent class's constructor?

Q5. What does polymorphism mean?

ℹ Answer Key
1-b, 2-b, 3-b, 4-c, 5-b

11.10  Module Assignment

Assignment: Institute Course Management OOP System

Expected Output: A working OOP-based course catalog system demonstrating inheritance, encapsulation, and polymorphism together in one script.

11.11  Interview Questions — Module 11


11.12  Student Notes Page

Use this space to write down key points, doubts, and your own examples from today's session.