Wednesday, 14 October 2026

Python Programming Through Gamification - Introduction to OOP and Classes & Objects : Day 2

Classes, Inheritance and Polymorphism — Explained with Everyday Examples

Imagine you are teaching programming to students who have never written a line of code. The easiest way to explain these three concepts is to connect them with things they see every day: students, vehicles, and payment methods.


1. What is a Class?

A class is a blueprint or design used to create objects.

Think about a house construction plan. An architect creates one blueprint, and builders use that blueprint to construct many houses. The houses may have different colours, owners, and sizes, but they follow the same basic design.

Country or town house project concept set, 3D isometric vector illustration of a small house building project, countryside small house in village or outskirt.

Everyday example: Student

A school maintains information about every student. Each student has a name, roll number, and age. A class defines what information every student should have and what actions they can perform.

  • Class: Student
  • Objects: Arun, Priya, Rahim
  • Attributes: Name, roll number, age
  • Methods: Attend class, write exam, display details

Student object

Name

Roll number

Student 1

Arun

101

Student 2

Priya

102

Student 3

Rahim

103

The Student class is the common blueprint, while Arun, Priya, and Rahim are individual objects created from it.

Simple Python example



class Student:
    def __init__(self, name, roll_no):
        self.name = name
        self.roll_no = roll_no

    def introduce(self):
        print("I am", self.name)

student1 = Student("Arun", 101)
student2 = Student("Priya", 102)

student1.introduce()
student2.introduce()

Output:

I am Arun
I am Priya

Remember: Class = Blueprint; Object = The actual thing created from that blueprint.

2. What is Inheritance?

Inheritance means creating a new class that reuses the properties and behaviours of an existing class.

Imagine a family. A child may inherit certain characteristics from their parents. Similarly, in programming, a child class can inherit attributes and methods from a parent class.

Inheritance in OOP. In our previous article, we explored… | by Rashmi Sandamini | Medium

medium.com

Everyday example: Vehicles

A car, bus, and motorcycle are all vehicles. They share some common features:

  • They have a brand.
  • They have a speed.
  • They can start and stop.

But each vehicle also has its own features.

  • A car has passenger seats and a boot.
  • A bus has a large passenger capacity.
  • A motorcycle has two wheels.

Instead of writing the same common features separately for every vehicle, we create a parent class called Vehicle.

Parent class

Child classes

Vehicle

Car

Vehicle

Bus

Vehicle

Motorcycle

The child classes inherit common features from Vehicle and can add their own specialised features.

Simple Python example


class Vehicle:

    def start(self):
        print("Vehicle started")

class Car(Vehicle):
    def open_boot(self):
        print("Car boot opened")

class Bus(Vehicle):
    def carry_passengers(self):
        print("Bus is carrying passengers")

car = Car()
bus = Bus()

car.start()       # Inherited method
car.open_boot()   # Car's own method

bus.start()       # Inherited method
bus.carry_passengers()

Output:

Vehicle started
Car boot opened
Vehicle started
Bus is carrying passengers

Notice that we wrote the start() method only once in the parent class. Both the car and bus can use it.

Remember: Inheritance = Reuse existing features and add specialised features.

3. What is Polymorphism?

The word polymorphism means many forms.

In programming, polymorphism allows the same method or command to produce different behaviours depending on which object uses it.

Think about the word “speak.” A dog barks, a cat meows, and a human talks. The action is broadly the same — speaking or making a sound — but the result differs.

Implementing Polymorphism (behind the scenes) | by Osman Yasal | Medium

osmyasal.medium.com

Everyday example: Different payment methods

Imagine an online shopping application with three payment options:

  • UPI: Pay using a UPI app.
  • Credit card: Pay using card details.
  • Cash on delivery: Pay when the order arrives.

The customer performs the same general action: pay().

However, each payment method handles the payment differently.

Simple Python example



class UPI:
    def pay(self, amount):
        print("Paid using UPI:", amount)

class CreditCard:
    def pay(self, amount):
        print("Paid using Credit Card:", amount)

class CashOnDelivery:
    def pay(self, amount):
        print("Pay on delivery:", amount)

payments = [UPI(), CreditCard(), CashOnDelivery()]

for method in payments:
    method.pay(500)

Output:

Paid using UPI: 500
Paid using Credit Card: 500
Pay on delivery: 500

The same method name, pay(), produces different results depending on the object.

Remember: Polymorphism = Same action, different behaviours.

Compare all three concepts

Home, Sweet Home. Blueprint Icon.

Class — Blueprint

Defines the attributes and methods that objects can have.

Example: Student class creates individual student objects.

Cartoon family tree vector illustration  ( asian family / nuclear family )

Inheritance — Reuse

A child class receives features from a parent class.

Example: Car inherits common features from Vehicle.

Payments concept. Payment method and option to transfer money.

Polymorphism — Different behaviours

The same method name can behave differently for different objects.

Example: Different payment objects implement pay() differently.

A practical classroom activity (without computers)

You can explain all three concepts in about 15 minutes using a board and a few students.

Activity 1: Design a student

Ask students to list what every student has in common: name, roll number, and age. Explain that the common design is the class. Ask three students to provide different details — these are the objects.

Activity 2: Build a vehicle family

Write Vehicle on the board. Draw branches to Car, Bus, and Bike. Ask students which features all three share and which are unique. This demonstrates inheritance.

Activity 3: Perform the same action differently

Ask one student to act like a dog, another like a cat, and another like a human speaking. Give everyone the instruction “make a sound.” The same instruction leads to different behaviours — polymorphism.

Python OOP: Classes, Objects, Attributes, Methods, Constructors and self

Chapter focus: Understanding how to organise information and actions in Python using real-world examples.

Main student deliverable: Create two Python classes — Student and AIDataset — and create objects from them.

Imagine you are developing a college management system or an AI application. You need to store student details and manage the data used to train an AI model. Python OOP (Object-Oriented Programming) helps you organise both tasks neatly.

1. Understand the six concepts through everyday life

Architect image temp classroom - 2.jpg | Aga Khan Academies

1. Class — The blueprint

A class is a design that specifies what information an object stores and what actions it can perform.

Example: Student is a blueprint for creating student records.

School, Student id card with photo. Vector illustration.

2. Object — The actual instance

An object is an individual item created using a class.

Example: Arun, Priya and Rahim are three different student objects.

Student identity card concept vector illustration on white background.

3. Attributes — The details

Attributes are the data associated with an object.

Example: A student's name, age, roll number and course.

Student girl raising hand in classes knowing answer to question. Vector in flat style, isolated teenage character, studying and learning activities. Female personage with laptop sitting by desk

4. Methods — The actions

Methods are functions defined inside a class that describe what its objects can do.

Example: introduce(), display_details() and calculate_average().

Student Registration Illustrations - Free Download in SVG, PNG

5. Constructor — The initial setup

A constructor-like initializer sets up an object when it is created. In Python, __init__() is commonly used for this.

Example: When registering a student, the system records the student's name, age and roll number.

Showing Id Card Illustrations - Free Download in SVG, PNG

6. self — This particular object

self refers to the current object whose method is running.

Example: When Arun's details are displayed, self.name refers to Arun's name, not Priya's.

2. Practical example 1: The Student class

Suppose a college has 1,000 students. Instead of writing separate variables and functions for every student, we can create one class and use it to make as many student objects as needed.

Python code



class Student:
    def __init__(self, name, roll_no, course):
        self.name = name
        self.roll_no = roll_no
        self.course = course

    def display_details(self):
        print("Name:", self.name)
        print("Roll Number:", self.roll_no)
        print("Course:", self.course)

    def introduce(self):
        print("Hello, I am", self.name)

student1 = Student("Arun", 101, "Data Analytics")
student2 = Student("Priya", 102, "Artificial Intelligence")

student1.display_details()
student2.display_details()

student1.introduce()

Expected Output:



Explain each line to students

Code

Layman's explanation

class Student:

Create the student blueprint.

def __init__(...)

Set up a new student's details.

self.name = name

Store the supplied name in this particular student object.

def display_details(self):

Define an action to display student details.

student1 = Student(...)

Create a student record for Arun.

student1.display_details()

Ask Arun's object to display its details.

 

Important distinction: name is the value passed into the initializer; self.name is the attribute stored on that particular object. self is a conventional parameter name, not a Python keyword, but it should be used by convention for instance methods.

3. Practical example 2: The AIDataset class

Now connect OOP with Artificial Intelligence.

Before an AI model can learn, it needs data. For example, an AI system that predicts student performance may use student attendance, assignment marks and examination scores.

An AIDataset class can store information about a dataset and provide actions to inspect it.

Data Science und Maschinelles Lernen - Datenmanagement im Maschinenbau (DMB) | Paderborn University

mb.uni-paderborn.de

Python code

 



class AIDataset:
    def __init__(self, name, rows, columns):
        self.name = name
        self.rows = rows
        self.columns = columns

    def display_info(self):
        print("Dataset:", self.name)
        print("Number of records:", self.rows)
        print("Number of features:", self.columns)

    def calculate_total_cells(self):
        return self.rows * self.columns

dataset1 = AIDataset("Student Performance", 100, 5)
dataset2 = AIDataset("Sales Data", 500, 8)

dataset1.display_info()
print("Total cells:", dataset1.calculate_total_cells())

dataset2.display_info()
print("Total cells:", dataset2.calculate_total_cells())

Expected Outcome:


Dataset: Student Performance
Number of records: 100
Number of features: 5
Total cells: 500

Dataset: Sales Data
Number of records: 500
Number of features: 8
Total cells: 4000

Explain this with a spreadsheet analogy

Imagine an Excel workbook:

  • Class: A reusable design for describing datasets.

  • Object: One particular dataset, such as Student Performance.

  • Attributes: Dataset name, number of rows and number of columns.

  • Methods: Display dataset information and calculate the number of cells.

  • Constructor: Initialise the dataset's details.

  • self: Refer to the specific dataset currently being examined.

Here, rows * columns gives the total number of cells in a simple rectangular dataset. It does not mean the AI model has been trained.

4. Let students experiment

Students can run the examples above in Google Colab, Jupyter Notebook or a local Python environment.

Python OOP Coding Exercise: Student Class

Beginner Level

Objective: Learn how to create a class, create an object, store attributes, define methods, and use self and __init__().

1. The task

Imagine you are developing a college student registration system.

Create a Python class called Student with the following requirements:

  1. Store the student's name, roll number and course.
  2. Use a constructor (__init__()) to initialise these details.
  3. Create a method called display_details() to display the student's information.
  4. Create an object named student1 with the following details:

Attribute

Value

Name

Kavitha

Roll number

120

Course

Artificial Intelligence

5. Call the display_details() method to display the information.

2. Try writing the code

Ask students to complete the missing parts before looking at the solution.


class Student:
    def __init__(self, name, roll_no, course):
        self.name = ______
        self.roll_no = ______
        self.course = ______

    def display_details(self):
        print("Student Name:", self.name)
        print("Roll Number:", self.roll_no)
        print("Course:", self.course)

# Create a student object
student1 = Student("Kavitha", 120, "Artificial Intelligence")

# Display the details
student1.________________()

3. Solution




class Student:
    def __init__(self, name, roll_no, course):
        self.name = name
        self.roll_no = roll_no
        self.course = course

    def display_details(self):
        print("Student Name:", self.name)
        print("Roll Number:", self.roll_no)
        print("Course:", self.course)

student1 = Student("Kavitha", 120, "Artificial Intelligence")

student1.display_details()

4. Expected output

Student Name: Kavitha

Roll Number: 120

Course: Artificial Intelligence

5. Explain the code in simple language

Code

Meaning

class Student:

Creates a blueprint for student records.

__init__()

Initialises the details when a new student object is created.

self.name = name

Stores the supplied name in this particular object.

self.roll_no = roll_no

Stores the student's roll number.

self.course = course

Stores the student's course.

student1 = Student(...)

Creates an object representing Kavitha.

student1.display_details()

Calls the method to display Kavitha's information.

6. Challenge exercises

After completing the basic program, ask students to make these changes independently:

  • Challenge 1: Create another object named student2 for Arun, roll number 121, studying Data Analytics.
  • Challenge 2: Add a new attribute called college_name.
  • Challenge 3: Create a method named introduce() that prints: Hello, my name is Kavitha.
  • Challenge 4: Change Kavitha's course and display the updated details.

Lesson takeaway: One class can create many objects, each with its own information. This is the basic idea behind Object-Oriented Programming (OOP) in Python.

 



Five questions to check understanding

  1. What is the difference between a class and an object?

  2. Why can two objects of the same class have different names?

  3. What is the purpose of __init__()?

  4. What does self.name mean?

  5. If a dataset has 200 rows and 10 columns, how many cells does it contain?

The key takeaway: A class is the design, an object is an individual instance, attributes store its information, methods define its actions, __init__() sets up its initial state, and self identifies the current object. Once students understand these six ideas, they have the foundation for inheritance, polymorphism and more advanced AI programming.

Responses

1. What is the difference between a class and an object? A class is a blueprint, and an object is created using that blueprint. Example: Student is a class; Kavitha is an object.

2. Why can two objects of the same class have different names? Each object stores its own data. Example: One student is Kavitha, and another is Arun.

3. What is the purpose of __init__()? It initialises an object's attributes when the object is created. Example: It sets a student's name and roll number.

4. What does self.name mean? It refers to the name stored in the current object.

5. If a dataset has 200 rows and 10 columns, how many cells does it contain? Answer: 2,000 cells.

Calculation: 200 × 10 = 2,000

Courtesy - 1(google search result for sales travel)

No comments:

Post a Comment