0% found this document useful (0 votes)
3 views18 pages

Module5 OOP Python

Module 5 covers Object-Oriented Programming (OOP) concepts in Python, including classes, pure functions, modifiers, special methods like __init__() and __str__(), operator overloading, and polymorphism. It provides definitions, examples, and advantages of each concept, emphasizing the importance of classes in organizing data and supporting code reusability. The module also highlights the differences between pure functions and modifiers, as well as operator overloading and polymorphism.

Uploaded by

nandanbs2006
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views18 pages

Module5 OOP Python

Module 5 covers Object-Oriented Programming (OOP) concepts in Python, including classes, pure functions, modifiers, special methods like __init__() and __str__(), operator overloading, and polymorphism. It provides definitions, examples, and advantages of each concept, emphasizing the importance of classes in organizing data and supporting code reusability. The module also highlights the differences between pure functions and modifiers, as well as operator overloading and polymorphism.

Uploaded by

nandanbs2006
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module – 5

Object-Oriented Programming in Python

Repeated Exam Questions with Model Answers

Contents
• 1. Class and Objects
• 2. Pure Functions and Modifiers
• 3. __init__() and __str__() Methods
• 4. Polymorphism / Operator Overloading
• 5. Prototyping vs Planning
• 6. Employee Class Program

Module 5 – OOP in Python Page 1


Q1. What is a Class? How do we define a class? How are class
members accessed? Explain with examples.
(Repeated 4 times — Very Important, 10 Marks)

Introduction
A class is a user-defined data type (or blueprint) used to create objects. It contains attributes (variables)
and methods (functions) that define the properties and behaviour of an object.

Definition
A class is a blueprint or template used to create objects. It groups data members (attributes) and
methods (functions) into a single unit.

Key Points
• A class is created using the class keyword.
• It is also called a programmer-defined data type.
• A class contains attributes and methods.
• A class acts as a blueprint for creating objects.
• One class can create many objects.
• Memory is allocated only when an object is created.

How to Define a Class


Syntax:
class ClassName:
"""Class Description"""

Example:
class Point:
"""Represents a point in 2-D space"""

• class — keyword used to define a class.


• Point — name of the class.
• """Represents a point in 2-D space""" — documentation string (optional).

Object (Instantiation)
An object is an instance of a class. Creating an object is called instantiation.

Syntax:
object_name = ClassName()

Example:
blank = Point()

• blank is an object.
• Point() creates an object of the class.

Module 5 – OOP in Python Page 2


Class Members
Class members are the attributes (variables) and methods (functions) inside a class.
blank.x = 3
blank.y = 4

Here, x and y are attributes of the object blank.

Accessing Class Members


Class members are accessed using the dot ( . ) operator.

Syntax:
object_name.member_name

Example:
blank.x = 3
blank.y = 4

print(blank.x)
print(blank.y)

Output:
3
4

Complete Example Program


class Point:
"""Represents a point in 2-D space"""

# Create an object
blank = Point()

# Assign values to attributes


blank.x = 3
blank.y = 4

# Access class members


print("Value of x =", blank.x)
print("Value of y =", blank.y)

Output:
Value of x = 3
Value of y = 4

Explanation
• A class named Point is created.
• An object blank is created using Point().
• Two attributes x and y are assigned values.
• The values are accessed using the dot operator ( . ).
• The output displays the values of the object attributes.

Module 5 – OOP in Python Page 3


Advantages of Classes
• Organizes data and functions together.
• Supports code reusability.
• Makes programs easy to understand and maintain.
• Allows creating multiple objects from one class.
• Supports Object-Oriented Programming (OOP).

Conclusion
A class is a blueprint used to create objects. It is defined using the class keyword. An object is created
by instantiation, and its members (attributes and methods) are accessed using the dot ( . ) operator.
Classes help organize programs, improve code reusability, and form the foundation of Object-Oriented
Programming in Python.

Q2. Explain the Concept of Pure Functions and Modifiers with


Python Code.
(Repeated 4 times — Very Important, 10 Marks)

Introduction
In Python, functions that operate on objects are mainly of two types: Pure Functions and Modifiers.
These functions help us perform different operations on objects.

1. Pure Functions

Definition
A pure function is a function that does not change (modify) the original objects passed to it. Instead, it
creates a new object, performs the operation, and returns the new object.

Characteristics of Pure Functions


• Does not change the original object.
• Creates a new object.
• Returns the new object.
• Has no side effects.
• Safe to use because the original data remains unchanged.
• Easy to understand and debug.
• Makes programs more reliable.

Syntax
def function_name(parameters):
# Create a new object
# Perform operations
return new_object

Module 5 – OOP in Python Page 4


Example Program
class Time:
pass

def add_time(t1, t2):


result = Time()
[Link] = [Link] + [Link]
[Link] = [Link] + [Link]
[Link] = [Link] + [Link]
return result

t1 = Time()
[Link] = 2
[Link] = 30
[Link] = 20

t2 = Time()
[Link] = 1
[Link] = 15
[Link] = 10

ans = add_time(t1, t2)


print([Link], [Link], [Link])

Output:
3 45 30

Explanation
• add_time() creates a new Time object called result.
• It adds the values of t1 and t2.
• The original objects (t1 and t2) are not changed.
• The function returns a new object.

Advantages of Pure Functions


• Original data is safe.
• Easy to test.
• Easy to debug.
• No unwanted changes in the program.
• Improves code reliability.

2. Modifiers

Definition
A modifier is a function that changes the original object passed to it, instead of creating a new object.

Characteristics of Modifiers
• Changes the original object.
• Does not create a new object.

Module 5 – OOP in Python Page 5


• Changes are visible outside the function.
• Saves memory because no new object is created.
• Useful when updating existing data.

Syntax
def function_name(object):
# Modify object

Example Program
class Time:
pass

def increment(time, seconds):


[Link] = [Link] + seconds
if [Link] >= 60:
[Link] = [Link] - 60
[Link] = [Link] + 1

t = Time()
[Link] = 2
[Link] = 30
[Link] = 50

increment(t, 20)
print([Link], [Link], [Link])

Output:
2 31 10

Explanation
• The function does not create a new object.
• It directly changes the values inside t.
• After adding 20 seconds, one minute is carried forward.
• The original object is modified.

Difference Between Pure Functions and Modifiers

Pure Function Modifier

Creates a new object Modifies the existing object

Original object is not changed Original object is changed

Returns a new object Usually does not return a new object

No side effects Has side effects

Easy to test and debug Slightly harder to debug

Module 5 – OOP in Python Page 6


Safer to use Useful for updating existing data

More reliable More memory efficient

Used when original data should Used when original data needs to be updated
remain unchanged

Conclusion
Pure functions create a new object and do not change the original object, making them safer and easier
to debug. Modifiers directly change the original object, making them faster and memory-efficient. Both
are useful depending on the program's requirement.

Q3. Explain __init__() and __str__() Methods with Examples.


(Repeated 4 times — Very Important, 10 Marks)

Introduction
In Python, __init__() and __str__() are special methods (magic methods) used in classes. __init__()
initializes an object when it is created, and __str__() returns a readable string representation of an
object. These methods make objects easy to create and display.

1. __init__() Method

Definition
The __init__() method is a special method that is automatically called when an object is created. It is
also known as the constructor, and it is used to initialize the object's attributes.

Key Points
• It is called automatically when an object is created.
• It is also called the constructor.
• It initializes object variables (attributes).
• It uses the self parameter to refer to the current object.
• Parameters can have default values.
• It reduces the need to assign values separately after object creation.

Syntax
class ClassName:
def __init__(self, parameter1, parameter2):
self.parameter1 = parameter1
self.parameter2 = parameter2

Example Program
class Time:

Module 5 – OOP in Python Page 7


def __init__(self, hour=0, minute=0, second=0):
[Link] = hour
[Link] = minute
[Link] = second

time = Time(9, 45, 30)

print([Link])
print([Link])
print([Link])

Output:
9
45
30

Explanation
• Time(9, 45, 30) creates an object.
• Python automatically calls __init__().
• The values are stored in hour, minute, and second.
• These values become the attributes of the object.

Advantages of __init__()
• Initializes object values automatically.
• Reduces repeated code.
• Makes object creation simple.
• Improves code readability.
• Allows default values.

2. __str__() Method

Definition
The __str__() method is a special method used to return a string representation of an object. It is
automatically called when the print() function is used on an object.

Key Points
• Automatically called by print(object).
• Must return a string.
• Makes the output easy to understand.
• Improves the appearance of object output.
• Used for displaying object information.

Syntax
class ClassName:

def __str__(self):
return "string"

Module 5 – OOP in Python Page 8


Example Program
class Time:

def __init__(self, hour, minute, second):


[Link] = hour
[Link] = minute
[Link] = second

def __str__(self):
return f"{[Link]}:{[Link]}:{[Link]}"

time = Time(9, 45, 0)

print(time)

Output:
9:45:0

Explanation
• The object time is created.
• When print(time) is executed, Python automatically calls the __str__() method.
• The returned string is displayed.

Combined Example (__init__() + __str__())


class Student:

def __init__(self, name, age):


[Link] = name
[Link] = age

def __str__(self):
return f"Name: {[Link]}, Age: {[Link]}"

s1 = Student("Rahul", 20)

print(s1)

Output:
Name: Rahul, Age: 20

Explanation
• __init__() initializes the student's name and age.
• __str__() returns the student's details as a readable string.
• print(s1) automatically calls __str__().

Difference Between __init__() and __str__()

__init__() __str__()

Initializes an object Returns string representation of an object

Module 5 – OOP in Python Page 9


Called during object creation Called when print() is used

Used to assign values Used to display values

Acts like a constructor Acts like a display method

Does not return a value Must return a string

Used for object initialization Used for object representation

Conclusion
__init__() is used to initialize an object when it is created, while __str__() is used to display an object in a
readable format. Both are special (magic) methods that make object creation and object display simple,
readable, and efficient in Python.

Q4. Explain Operator Overloading and Polymorphism with Examples.


(Repeated 2 times — Very Important, 10 Marks)

Introduction
Operator overloading and polymorphism are important concepts in Object-Oriented Programming
(OOP). Operator overloading allows operators such as +, -, * to work with user-defined objects, while
polymorphism allows the same function or method to work with different types of objects.

1. Operator Overloading

Definition
Operator overloading is the process of giving new meaning or behaviour to an existing operator when it
is used with objects of a user-defined class. Python uses special methods (magic methods) such as
__add__() and __sub__() to overload operators.

Key Points
• Allows operators to work with user-defined objects.
• Uses special methods called magic methods.
• Makes programs simple and readable.
• Improves code reusability.
• Supports Object-Oriented Programming.

Common Operator Overloading Methods

Operator Special Method

+ __add__()

Module 5 – OOP in Python Page 10


- __sub__()

* __mul__()

/ __truediv__()

== __eq__()

< __lt__()

Syntax
def __add__(self, other):
# code

Example Program
class Number:

def __init__(self, value):


[Link] = value

def __add__(self, other):


return Number([Link] + [Link])

def __str__(self):
return str([Link])

n1 = Number(10)
n2 = Number(20)

result = n1 + n2
print(result)

Output:
30

Explanation
• n1 + n2 automatically calls the __add__() method.
• The values 10 and 20 are added.
• A new object with value 30 is returned.
• print(result) calls the __str__() method.

Advantages of Operator Overloading


• Makes code simple and readable.
• Reduces complexity.
• Improves code reusability.
• Supports user-defined data types.
• Makes objects behave like built-in data types.

Module 5 – OOP in Python Page 11


2. Polymorphism

Definition
Polymorphism means "many forms". It allows the same function or operation to work with different types
of objects.

Key Points
• Means one interface, many forms.
• Same function works with different data types.
• Increases flexibility.
• Reduces duplicate code.
• Improves code reusability.

Example 1: Built-in Polymorphism


The len() function works with different data types.
print(len("Python"))
print(len([10, 20, 30]))
print(len((1, 2, 3, 4)))

Output:
6
3
4

The same len() function works for a string, a list, and a tuple — this is polymorphism.

Example 2: User-Defined Polymorphism


class Dog:
def sound(self):
print("Dog barks")

class Cat:
def sound(self):
print("Cat meows")

def animal_sound(animal):
[Link]()

d = Dog()
c = Cat()

animal_sound(d)
animal_sound(c)

Output:
Dog barks
Cat meows

Explanation

Module 5 – OOP in Python Page 12


• The function animal_sound() is used for both Dog and Cat.
• It calls the appropriate sound() method based on the object.
• This is an example of polymorphism.

Difference Between Operator Overloading and Polymorphism

Operator Overloading Polymorphism

Gives new meaning to operators Same function works with different objects

Uses special methods like __add__() Uses same method/function for many forms

Used with operators Used with functions and methods

Makes operators work with objects Makes code flexible and reusable

Example: + for objects Example: len() works on strings, lists, tuples

Conclusion
Operator overloading allows operators like +, -, * to work with user-defined objects using special
methods such as __add__(). Polymorphism allows the same function or method to work with different
types of objects. Both concepts improve code readability, reusability, flexibility, and maintainability in
Python.

Q5. Explain the Concept of Prototyping vs Planning.


(Repeated 2 times — Important, 10 Marks)

Introduction
While developing a program, there are two common approaches: Prototyping (Prototype and Patch)
and Planning (Designed Development). Both methods help in solving programming problems, but they
follow different approaches.

1. Prototyping (Prototype and Patch)

Definition
Prototyping means first creating a simple working version (prototype) of the program. After testing it,
errors are corrected and new features are added step by step. It is also called the Prototype and Patch
approach.

Steps in Prototyping
• Understand the problem.
• Create a simple working program (prototype).
• Test the program.

Module 5 – OOP in Python Page 13


• Find and fix errors (patches).
• Add more features.
• Repeat until the program is complete.

Features of Prototyping
• Starts with a simple program.
• Errors are fixed gradually.
• New features are added step by step.
• Easy to understand.
• Gives quick results.
• Suitable for small projects.

Advantages
• Easy to develop.
• Quick to build.
• Easy to test.
• User feedback can be taken early.
• Errors can be corrected gradually.
• Good for learning and experimenting.

Disadvantages
• Program may become difficult to maintain.
• Code quality may reduce after many patches.
• Design may not be well organized.
• Not suitable for large projects.

2. Planning (Designed Development)

Definition
Planning means carefully analyzing the problem, designing the solution, and then writing the program. It
is also called Designed Development.

Steps in Planning
• Study the problem carefully.
• Design the solution.
• Decide the algorithm.
• Write the program.
• Test the program.
• Correct any errors.

Features of Planning
• Complete design is prepared first.

Module 5 – OOP in Python Page 14


• Better program structure.
• Fewer errors.
• Easy to maintain.
• Suitable for large projects.
• Produces efficient programs.

Advantages
• Produces clean code.
• Easy to maintain.
• Better performance.
• Less chance of mistakes.
• Suitable for complex applications.
• Saves time in the long run.

Disadvantages
• Takes more time at the beginning.
• Requires careful analysis.
• Changes are difficult after coding starts.
• Not suitable when requirements change frequently.

Example: Adding Two Time Objects

In Prototyping:
• First, write a simple function to add hours, minutes, and seconds.
• Test the output.
• If minutes or seconds become greater than 60, modify the program.
• Keep improving until the correct result is obtained.

In Planning:
• First, think about how time should be represented.
• Convert the time into total seconds.
• Add the seconds.
• Convert the result back into hours, minutes, and seconds.
• This gives a cleaner and more efficient solution.

Difference Between Prototyping and Planning

Prototyping Planning

Build first, improve later Plan first, then build

Simple prototype is created Complete design is prepared

Module 5 – OOP in Python Page 15


Errors fixed gradually Fewer errors from the beginning

Faster initial development More time needed for planning

Best for small projects Best for large projects

Code may become messy Code is clean and organized

Easy to modify Changes are harder later

Also called Prototype and Patch Also called Designed Development

Conclusion
Prototyping means creating a simple working model first and then improving it by fixing errors and
adding features. Planning means designing the complete solution before coding, resulting in cleaner and
more efficient programs. Prototyping is suitable for small projects and quick development, while Planning
is suitable for large and complex projects where good design and maintenance are important.

Q6. Define Classes and Objects in Python. Create a Class Called


Employee and Initialize It with Employee ID and Name. Design
Methods to Set Age, Set Salary, and Display All Information.
(10 Marks)

Introduction
Python supports Object-Oriented Programming (OOP). The two basic concepts of OOP are class and
object.

Class
A class is a user-defined data type that contains data members (attributes) and methods (functions). It
acts as a blueprint or template used to create objects.

Object
An object is an instance of a class that contains actual data. It is created from the class and is used to
access the class members.

Program
class Employee:

# Constructor to initialize employee id and name


def __init__(self, emp_id, name):
self.emp_id = emp_id
[Link] = name
[Link] = 0
[Link] = 0

Module 5 – OOP in Python Page 16


# Method to assign age
def setAge(self, age):
[Link] = age

# Method to assign salary


def setSalary(self, salary):
[Link] = salary

# Method to display employee details


def display(self):
print("Employee ID :", self.emp_id)
print("Employee Name :", [Link])
print("Age :", [Link])
print("Salary :", [Link])

# Create object
emp = Employee(101, "Rahul")

# Set age and salary


[Link](25)
[Link](50000)

# Display details
[Link]()

Output:
Employee ID : 101
Employee Name : Rahul
Age : 25
Salary : 50000

Explanation

1. Class Creation
class Employee:

Creates a class named Employee.

2. Constructor (__init__())
def __init__(self, emp_id, name):

• Initializes the employee ID and name.


• Also initializes age and salary with default value 0.

3. setAge() Method
def setAge(self, age):
[Link] = age

Assigns the employee's age.

4. setSalary() Method

Module 5 – OOP in Python Page 17


def setSalary(self, salary):
[Link] = salary

Assigns the employee's salary.

5. display() Method
def display(self):

Displays all employee details such as Employee ID, Employee Name, Age, and Salary.

6. Object Creation
emp = Employee(101, "Rahul")

Creates an object named emp.

7. Calling Methods
[Link](25)
[Link](50000)
[Link]()

Uses the object to set age, set salary, and display employee details.

Advantages
• Organizes employee data in one class.
• Easy to create multiple employee objects.
• Improves code reusability.
• Makes the program easy to understand and maintain.
• Supports Object-Oriented Programming.

Conclusion
An Employee class is created with employee ID and name initialized using the __init__() method. The
methods setAge() and setSalary() assign age and salary, while the display() method prints all employee
information. This demonstrates the use of classes, objects, constructors, and methods in Python.

Module 5 – OOP in Python Page 18

You might also like