Python Programming Module-4 VTU QP Solution (21EC643) by Prof. Sujay Gejji
Python Programming Module-4 VTU QP Solution (21EC643) by Prof. Sujay Gejji
Module 4 :
Define class and object? What are programmer defined types? Explain with example Jan 20
What is a Class? How to define a class in Python? How to initialize a class and how the class members
are accessed? July 19
Define class and object? How class can be instantiated in python? Jan 19
Explain classes and attributes in python language with examples. June 20
Solution:
• Class is user (programmer) defined data type which binds data and functions together into
single entity. Class is just blue print or logical entity
• An object is an instance of a class and it has physical existence. One can create any
number of objects for a class.
• The process of creating a new object is called as instantiation
• Object can be created by assigning class name to variable.
• The class is created using class keyword
• The variables associated with class are called attributes
Example :
class Rectangle:
def __init__(self, height, width):
self. height = height
self. width = width
def area(self):
y1= self.height * self.width
return y1
def perimeter(self):
y2= (self.height + self.width)*2
return y2
Explanation:
• Class rectangle is defined,
• Within class, 2 functions(methods) are defined: area and perimeter
• Input values are accepted from user.
• Create the class object:
• Call the functions (methods)
• Print the result
Write a class Rectangle that has attributes length and breadth and a method area which returns the
area of the rectangle June 2020
Define a class for rectangle and write a function called area-rectangle that takes a rectangle
object as argument and calculates the area. Explain the code segment. Jan 22
class Rectangle:
def __init__(self, height, width):
self. height = height
self. width = width
def area(self):
return self.height * self.width
def perimeter(self):
return (self.height + self.width)*2
Another way of writing the program (passing rect object to the function )
class Rectangle:
def __init__(self, height, width):
self.height = height
self.width = width
#defining the function outside the class, and passing the object as parameter
def area_rectangle(rect):
return rect.height * rect.width
1. How class can be instantiated in python? Write a python program to express instances as return
values to define a class RECTANGLE with members width, height, corner_x, corner_y, and
member function: to find centre, area and perimeter of a rectangle.
Solution:
Instantiation
• The process of creating a new object is called as instantiation. Object can be created by
assigning class name to variable.
• An object is an instance of a class and it has physical existence. One can create any
number of objects for a class.
• The class is created using class keyword.
• Attributes are the variables associated with class
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
class Rectangle:
def __init__(self, width, height, corner_x=0, corner_y=0):
self.width = width
self.height = height
self.corner = Point(corner_x, corner_y)
def find_center(self):
center_x = self.corner.x + self.width / 2
center_y = self.corner.y + self.height / 2
center_point = Point(center_x, center_y)
return center_point
def find_area(self):
return self.width * self.height
def find_perimeter(self):
return 2 * (self.width + self.height)
Here, this function takes an object self (object of rectangle) as an argument. And this function
returns the object of class point.
Create a student class and initialize it with name and roll number. Design methods to:
i. Display_to display all information of the student.
ii. setAge_to assign age to student.
iii. setMarks_to assign marks to the student
class Student:
def __init__(self, name, roll_number):
self.name = name
self.roll_number = roll_number
self.age = None
self.marks = None
def display(self):
print("Name:", self.name)
print("Roll Number:", self.roll_number)
print("Age:", self.age)
print("Marks:", self.marks)
# Create object1
student1 = Student("Sachin", "25")
# Create object2
student2 = Student("Rohit", "26")
# Call the functions
student2.set_age(20)
student2.set_marks(90)
student2.display()
What is operator overloading? Write python code to overload “+” ”-“ and “*” operator by providing
the methods_ _add_ _, _ _sub_ _ and _ _ mul_ _. June 2020
Operator overloading:
class A:
def __init__(self, x):
self.x = x
Output:
30
-10
200
With examples explain Pure functions and modifier Jan 22, June 2020
What is a pure function? Write a python program to find duration of event if start and end time is given by
defining class TIME Jan 19
Pure Functions:
Pure functions are functions that do not modify the state of the objects.
These functions take input parameters, perform some computation, and return a result without
altering the original objects. Pure functions produces the result only based on their input arguments
and do not modify any state of the object.
Most of the pure functions are fruitful functions.
Modifiers (or Mutators):
Modifiers, are functions that modify the state of the objects.
These functions change the properties of an object. Modifiers can alter the object's state by updating
its attributes (values)
Modifier functions return nothing or void
Pure function:
To Write a function to add 2-time objects & to print time in HH:MM: SS format
class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
def display_time(self):
print(f'{self.hour:02d}:{self.minute:02d}:{self.second:02d}')
• We have created the class Time (blank class). Then we have defined functions add_time and
display_time
• Here, the function add_time() takes two arguments self and t2, and returns a Time object,
whereas, it is not modifying contents of t1 and t2. Such functions are called as pure
functions
Modifiers
Example: User defined Function which converts seconds to the minutes and hours
Function
There are two types of functions
o pure functions
o modifiers.
self.second = second
def display_time(self):
print(f'{self.hour:02d}:{self.minute:02d}:{self.second:02d}')
• We have created the class Time. Then we have defined 2 functions add_time and disp_time
• Here, the function add_time() takes two arguments of type Time, and returns a Time object,
whereas, it is not modifying contents of t1 and t2. Such functions are called as pure functions
self.hour = hour
self.minute = minute
self.second = second
def display_time(self):
print(f'{self.hour:02d}:{self.minute:02d}:{self.second:02d}')
Define attribute? With the help of python code, explain how function returns instance values
• Class attributes are variables of a class that are shared between all of its objects or instances.
• The instance variables are specific to the instance and these are not shared among other
instances
Program to find the area of rectangle and distance between 2 points
Here, this function takes an object rect (object of rectangle) as an argument. Here rect and box
are the aliases. This function returns the object of class point.
Explain __init__ and str method with an example python program Jan19
Show using a Python code how _init_ method is invoked when an object is initiated. Explain its
working. July 18
Explain the need for INIT method. Demonstrate the use of init method for a class Time. Jan 22
• The init method is a special method, also known as the constructor, used to
initialize the attributes of an object.
• It is automatically called when a new instance(object) of a class is created.
• The init method is defined within the class and it takes the self parameter as the first
argument.
• The self parameter represents the default object of the class
• By using the "self" keyword we can access the attributes and methods of the class.
Example:
class Rectangle:
def area(self):
return self.height * self.width
def perimeter(self):
return (self.height + self.width)*2
The str method is a special method, which is used to represent objects as strings or simply
convert object data type to string format
The print() function in Python is suitable for printing basic data types such as numbers and stringsand
it has limited capabilities for printing the user-defined types (Class objects).
str method, is used to enhance the display or printing options for objects. So, first we have to
define the str__ method in the a class, then mention the desired string representation of the object, so
that object can be printed or displayed, the way we want.
Now whenever we use functions like str() or print() to print object, then Python automatically calls
the __str__ method to get the string representation and objects are printed in desired manner
Example:
#implementation of str method
class Student():
def init (self,name, roll_name):
self.name = name
self.roll_no= roll_name
Output:
My name is Dhoni and Roll no is 20
Explain the need for INIT method. Demonstrate the use of init method for a class Time.
(Note : init is short from of “initialization”)
• The init method is a special method, also known as the constructor, used to
initialize the attributes of an object.
• It is automatically called when a new instance(object) of a class is created.
• The init method is defined within the class and it takes the self parameter as the first
argument.
• The self parameter represents the default object of the class
• By using "self" keyword we can access the attributes and methods of the class.
• The double underscores at both sides of the __init__() method indicate that Python will use the
method internally.
Program:
Let us define a class called Time that records the time of day
class Time():
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
Output
11:58.20
Polymorphism
[Poly = many and morphism= forms, Polymorphism means many forms ]
• In programming, Polymorphism refers to a function having the same name being in used in different
ways in different situations. The object or method exhibits different behaviour in different contexts.
def histogram(str):
str = 'dhonii'
print(histogram(str))
Code explanation:
• Now, create user defined function with name histogram() and pass the string s as input
• In the histogram function, we create one empty dictionary to keep track of count of each letter.
• Then, using for loop, iterate each character i in the string s.
• Inside the loop, it checks if the character i is already a key in the dictionary d.
• If it is not present, then it adds that character as a key in the dictionary d with a value of 1, indicating
the first occurrence of that letter.
• If it is already present, it increments the value associated with that key by 1, indicating another
occurrence of the same letter.
• Here all the characters of string are assigned as KEYS of dictionary and occurrence of the each
character as values of the key
• Once the loop completes, the function returns the dictionary d.
• In this dictionary, 'd', 'h', 'i', 'n', and 'o' are KEYS and 1, ,1,2,1,1 are values
• This example demonstrates polymorphism since histogram function can handle different data types
• This function also for lists, tuples, and even dictionaries etc
• Functions which work with several types are called polymorphic.
Explain Polymorphism
• Poly = many and morphism= forms; Polymorphism means having multiple forms.
• Polymorphism means object or method exhibits different behaviour in different contexts.
Function having the same name behaves differently in different situations
• Polymorphism in operators: The + operator can be used to add the 2 integers and also it can
be used to concatenate the 2 lists or tuples.
Example1:
a = 23
b = 11
print(a+b) #addition of 2 integers
Output: 23
s1 = "Hello"
s2 = "Dhoni"
print(s1+ s2) #concatenation of string
Output: Hello Dhoni
• Polymorphism in in-built functions:
In case of len () function, if the input is string, it counts every letter in it. But if the input is
tuple or a dictionary, it processes them differently.
• Polymorphism in user-defined methods:
We can create methods with same name in different classes. Here the function with same
name called area is in 2 different classes. The function area behaves as per the context
Example:
class Rectangle:
def __init__(self, length, breadth):
self.l = length
self.b = breadth
def area(self):
return self.l * self.b
class Circle:
def __init__(self, radius):
self.r = radius
def area(self):
return pi * self.r ** 2
Histogram function to count the number of times each letter appears in a word
def histogram(str):
d = dict() # create an empty dictionary
for i in str: # iterate over the characters in the input string 's'
if i in d: # if the character 'i' is already a key in the dictionary
d[i] = d[i] + 1 # increment the count (value) of the character by 1
else:
d[i] = 1 # if the character 'i' is not present, add it to the dictionary with a value of 1
return d
str = 'dhonii'
print(histogram(str))
Code explanation:
• Now, create user defined function with name histogram() and pass the string s as input
• In the histogram function, we create one empty dictionary to keep track of count of each letter.
• Then, using for loop, iterate each character i in the string s.
• Inside the loop, it checks if the character i is already a key in the dictionary d.
• If it is not present, then it adds that character as a key in the dictionary d with a value of 1, indicating
the first occurrence of that letter.
• If it is already present, it increments the value associated with that key by 1, indicating another
occurrence of the same letter.
• Here all the characters of string are assigned as KEYS of dictionary and occurrence of the each
character as values of the key
• Once the loop completes, the function returns the dictionary d.
• In this dictionary, 'd', 'h', 'i', 'n', and 'o' are KEYS and 1, ,1,2,1,1 are values
• This example demonstrates polymorphism since histogram function can handle different data types
• This function also for lists, tuples, and even dictionaries etc
• Functions which work with several types are called polymorphic.
Write a program that uses class to store the name and marks of students. Uses list to store the marks
in three subjects
class students:
count = 0
def __init__(self, name):
self.name = name
self.marks = []
students.count = students.count + 1
def enterMarks(self):
for i in range(3):
m = int(input("Enter the marks of %s in %d subject: "%(self.name, i+1)))
self.marks.append(m)
def display(self):
print (self.name, "got ", self.marks)
s2.displayCount()
def area(self):
return self.height * self.width
def perimeter(self):
return (self.height + self.width)*2
def area(self):
return self.height * self.width
def perimeter(self):
return (self.height + self.width)*2
def add(self):
y = self.a + self.b
return y
#Child class
# Child class inheriting from the Solve class
class Child_Solve(Parent_Solve):
def multiply(self):
z = self.a * self.b
return z
# call the add method from the parent class using child object
#It means child class have all the methods and variables of parent
class
Result1 = obj.add()
print("Sum:", sum_result)
# Parent class 1
class Parent1:
def method1(self):
print("This is method 1 from Parent 1")
# Parent class 2
class Parent2:
def method2(self):
print("This is method 2 from Parent 2")
class Child3(Parent1):
def method5(self):
print("This is method 5 from Child 3")
Inheritance: In inheritance, child class inherits properties of parent class. Child class can access
all the data members and functions defined in the parent class
1. Simple Inheritance
In simple inheritance, a derived class inherits from a single base class
Example:
# Base (parent) Class
class Parent1:
def __init__(self, a=0, b=0):
self.a = a
self.b = b
def add(self):
y = self.a + self.b
return y
# Child class
class Child1(Parent1):
def div(self):
z = self.a / self.b
return z
# By using child class object, call the function of parent class & child class
Y1 = obj.add()
print(Y1)
Explanation:
• Child1 class inherits from Parent1. It can use the add method from the Parent1 class and
also define its own multiply method.
2. Multiple Inheritance
In multiple inheritance, a child class inherits from more than one base class.
Example:
# Base (parent) Classes
class Parent1:
def __init__(self, a=0, b=0):
self.a = a
self.b = b
def add(self):
y = self.a + self.b
return y
class Parent2:
def __init__(self, a=0, b=0):
self.a = a
self.b = b
def mul(self):
y = self.a * self.b
return y
# By using child object, we can call the function of parent class as well as child class
# Calling method from the Parent1 class
Y1 = obj.add()
print(Y1)
#multi-level inheritance
In multi-level inheritance, a derived(child) class inherits from another derived (child) class
def add(self):
y = self.a + self.b
return y
class Parent2:
def __init__(self, a=0, b=0):
self.a = a
self.b = b
def mul(self):
y = self.a * self.b
return y
# By using Child2 object, we can call the function of parent class & child class
# Calling method from Parent1 class
Y1 = obj.add()
print(Y1)
def display_time(self):
print(f'{self.hour:02d}:{self.minute:02d}:{self.second:02d}')
class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
def display_time(self):
print(f'{self.hour:02d}:{self.minute:02d}:{self.second:02d}')
• Drawback: But, this type of incremental development may end-up in unnecessary code,
with many special cases and it may become unreliable.
Designed development
• Designed development involves thorough planning before coding.
• It requires a deep understanding of the problem statement, including possible inputs and
edge cases, and how the function should behave.
Planned Code:
class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
def display_time(self):
print(f'{self.hour:02d}:{self.minute:02d}:{self.second:02d}')
o This approach ensures that your code is well-structured and easy to extend.
Here it is well planned and while is used instead of if statement to handle the overflow.
rect.width = rect.width + 50
rect.height = rect.height + 100
Here, rect is an instance of the Rectangle class. By adding 50 to rect.width and 100 to rect.height, we
changed its dimensions. This shows mutability because the original attributes (width and height) are
modified directly.
Example 2:
def resize(self, w, h):
self.width += w
self.height += h
return [self.width, self.height]
The values w and h are added to width and height. Hence the size of rectangle is modified.
This shows that objects are mutable.
Write a function to called print time that takes a time object and print it in the form of hour:
minute: second
class Time:
def __init__(self, hour, minute, second):
self.hour = hour
self.minute = minute
self.second = second
def print_time(time):
print(f'{time.hour:02}:{time.minute:02}:{time.second:02}')