Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
201 views

Python Programming Module-4 VTU QP Solution (21EC643) by Prof. Sujay Gejji

Python Programming Module-4 VTU QP Solution (21EC643) Notes by Prof. Sujay Gejji

Uploaded by

sujay g
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
201 views

Python Programming Module-4 VTU QP Solution (21EC643) by Prof. Sujay Gejji

Python Programming Module-4 VTU QP Solution (21EC643) Notes by Prof. Sujay Gejji

Uploaded by

sujay g
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

PYTHON APPLICATION PROGRAMMING

Module 4 :

OBJECT ORIENTED PROGRAMMING IN PYTHON

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

a = int(input("Enter height of rectangle: "))


b = int(input("Enter width of rectangle: "))

#Creating the objects


obj = Rectangle(a, b)

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

#Calling the methods


y=obj.area() # function call using object
z=obj.perimeter() # function call using object

#Printing the result


print(f'The area of rectangle: {y}’)
print(f'The Perimeter of rectangle: {z}')

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

a = int(input("Enter height of rectangle: "))


b = int(input("Enter width of rectangle: "))

obj = Rectangle(a, b)#Creating the object&__init__() is called automatically

y=obj.area() # function call using object


z=obj.perimeter() # function call using object

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

print('The area of rectangle:', y)


print('The Perimeter of rectangle:', z)

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

# Creating an object of the Rectangle class


rect = Rectangle(5, 10)

# Calculating the area by passing the object to the function


result = area_rectangle(rect)

# Printing the result


print(f'The area of the rectangle is: {result}’)

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

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

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)

# Creating an object of the Rectangle class


box = Rectangle(100, 200)

center = box.find_center() # object of Point class as return value


print(f"The center of the rectangle is: {center}")

area = box.find_area() # Numeric value as return value


print(f"The area of the rectangle is: {area}")

perimeter = box.find_perimeter() # Numeric value as return value


print(f"The perimeter of the rectangle is: {perimeter}")

• Functions can return instances (objects).


• For example, find_center(self) takes object of rectangle as argument and returns the object of
Point
method to find the centre of rectangle (object of rectangle is passed)
def find_center(self):

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

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

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)

def set_age(self, age):


self.age = age

def set_marks(self, marks):


self.marks = marks

# Create object1
student1 = Student("Sachin", "25")

# Call the functions


student1.set_age(20)
student1.set_marks(85)
student1.display()

# Create object2
student2 = Student("Rohit", "26")
# Call the functions

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

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

Explain operator overloading with examples Jan 2022

• Operator overloading means, ability of a built-in operator to behave differently according to


the different operands.
• It is a case of polymorphism, operators have different implementations based on operands or
parameters
• For example, the operator ‘+’ is used to:
o Add two integers.
o Concatenate two strings.
o Merge two lists.
o Add two objects

Operator overloading:

• Basic operators like +, -, * etc. can be overloaded.


• Python provides some special function or magic functions for operator overloading

Example: To overload the '+' operator


To overload '+' operator, we have to use the __add__ special method.
Program to overload the ‘+’, ‘-‘, ‘*’, operators

class A:
def __init__(self, x):
self.x = x

# adding two objects


def __add__(self, other):
return self.x+ other.x

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

# subtarcting two objects


def __sub__(self, other):
return self.x - other.x

#multiplying two objects


def __mul__(self, other):
return self.x * other.x

p1=A(10) # creating object


p2=A(20)
print (p1+p2)
print (p1-p2)
print(p1*p2)

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

Explain the concept of modifier with python code Jan 20

Explain pure functions and modifiers with python code

There are two types of functions


o pure functions
o modifiers.

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

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

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 add_time(self, t2):


sum_hour = self.hour + t2.hour
sum_minute = self.minute + t2.minute
sum_second = self.second + t2.second

if sum_second >= 60:


sum_second -= 60
sum_minute += 1

if sum_minute >= 60:


sum_minute -= 60
sum_hour += 1

return Time(sum_hour, sum_minute, sum_second)

def display_time(self):
print(f'{self.hour:02d}:{self.minute:02d}:{self.second:02d}')

# Creating object and initializing the values


t1 = Time(2, 10, 50)
t1.display_time()

# Creating the second time object and initializing the values


t2 = Time(1, 20, 20)
t2.display_time()

# Adding the two time objects


t3 = t1.add_time(t2)
t3.display_time()

• 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

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Modifiers
Example: User defined Function which converts seconds to the minutes and hours

def increment(time, seconds):


time.seconds = time.seconds +seconds #here seconds is argument, its value is changed

while time.seconds >= 60:


time.seconds = time.seconds - 60
time.minutes = time.minutes + 1

while time.minutes >= 60:


time.minutes = time.minutes - 60
time.hours = time.hours + 1

• In this function, initially we will add the seconds to time.seconds.


• If time.second is more than 60, for example if it is 350, then .we subtract the time.seconds by
60 and increment the time.minutes till the time.second becomes lesser than 60.
• Similarly, If time.minutes is more than 60, for example if it is 350, then .we subtract the
time.minute by 60 and increment the time.hours till the time.minutes becomes lesser than 60
• Note that, the modification is done on the object (argument) time itself. Thus, the above
function is a modifier.

Or you can give this example & explanation

Function
There are two types of functions
o pure functions
o modifiers.

Pure Functions (Fruitful function)


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
modifying the original objects. Pure functions produces the output only based on their input
arguments and do not modify any state of the object.
Most of the pure functions are fruitful functions.
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

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

self.second = second

def add_time(self, t2):


sum_hour = self.hour + t2.hour
sum_minute = self.minute + t2.minute
sum_second = self.second + t2.second

if sum_second >= 60:


sum_second= sum_second- 60
sum_minute = sum_minute +1

if sum_minute >= 60:


sum_minute = sum_minute- 60
sum_hour = sum_hour+ 1

return Time(sum_hour, sum_minute, sum_second)

def display_time(self):
print(f'{self.hour:02d}:{self.minute:02d}:{self.second:02d}')

# Creating object and initializing the values


t1 = Time(2, 10, 50)
t1.display_time()

# Creating the second time object and initializing the values


t2 = Time(1, 20, 20)
t2.display_time()

# Adding the two time objects


t3 = t1.add_time(t2)
t3.display_time()

• 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

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.
The functions that perform such modifications are known as modifier function.
Example: To write user defined function called increment, to add the seconds to a Time object.
class Time:
def __init__(self, hour=0, minute=0, second=0):

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

self.hour = hour
self.minute = minute
self.second = second

def display_time(self):
print(f'{self.hour:02d}:{self.minute:02d}:{self.second:02d}')

def modify_time(self, seconds):


self.second =self.second+ seconds

if self.second >= 60:


self.second -= 60
self.minute += 1

if self.minute >= 60:


self.minute -= 60
self.hour += 1

# Creating a time object and initializing the values


t = Time(2, 10, 50)
t.display_time()

# Modifying the time object


t.modify_time(30)
t.display_time()

• In this function, initially we will add the seconds to time.second.


• If time.second is more than 60, for example if it is 350, then .we subtract the time.second by
60 and increment the time.minute till the time.second becomes lesser than 60.
• Similarly, If time.minute is more than 60, for example if it is 350, then .we subtract the
time.minute by 60 and increment the time.hour till the time.minute becomes lesser than 60
• Note that, the modification is done on the object (argument) time itself. Thus, the above
function is a modifier.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

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

method to find the centre of rectangle (object of rectangle is passed)


def find_center(rect): #box and rect are aliases
p=Point() #point object is created
p.x = rect.corner.x + rect.width/2
p.y = rect.corner.y + rect.height/2
return p # returning point object

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 initialization method with example (__init__) June 2020

Explain the need for INIT method. Demonstrate the use of init method for a class Time. Jan 22

The init Method

(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 the "self" keyword we can access the attributes and methods of the class.

Example:

class Rectangle:

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

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

a = int(input("Enter height of rectangle: "))


b = int(input("Enter width of rectangle: "))

obj = Rectangle(a, b)#Creating the object&__init__() is called automatically

y=obj.area() # function call using object


z=obj.perimeter() # function call using object

print('The area of rectangle:', y)


print('The Perimeter of rectangle:', z)

Explain this program in your own words

The str Method

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

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

def str (self):


return "My name is %s and Roll no is %d" %(self.name,self.roll_no)

s = Student("Dhoni", 20) # Creating the object


print(s) # When we print an object, Python invokes the str method:

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

def display(t): #Method defined inside the class


print('%2d: %2d : %2d' %(t.hour, t.minute, t.second))

t=Time(11,58,20) #The method_init is called implicitly


t. display()

Output
11:58.20

Program Explanation: In above program,

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

• We have defined a class named Time


• The data attributes(variables) of this class are hour, minute and second.
• One method by name display is defined within the class. The parameters passed to this
method are
• The special method _init__ is called implicitly, when object of class Time is created. It
initiates the attributes
• Finally, values are displayed using display method

Differentiate the Function and Method.

Difference between Method and class


• A function which is defined inside the class is known as a method.
• Methods are semantically the same as functions, but there are two syntactic differences:
o Methods are defined inside a class definition in order to make the relationship between
the class and the method explicit.
o The syntax for invoking a method is different from the syntax for calling a function

Define polymorphism. Demonstrate polymorphism with function to find histogram to count


the numbers of times each letter appears in word and in sentence

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.

User defined function: Histogram


Histogram function to count the number of times each letter appears in a word

def histogram(str):

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

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

Histogram function as Polymorphism

• 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

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

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

# Initialize the classes


rec = Rectangle(5,3)
cir = Circle(4)

y=rec.area() #function call to calculate area of rectangle


print(y)

z=cir.area() #function call to calculate area of circle


print(z)

Another example for polymorphism


User defined function: Histogram

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

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

Histogram function as Polymorphism

• 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)))

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

self.marks.append(m)

def display(self):
print (self.name, "got ", self.marks)

name = input("Enter the name of Student:")


s1 = students(name)
s1.enterMarks()
s1.display()
print ("")

name = input("Enter the name of Student:")


s2 = students(name)
s2.enterMarks()
s2.display()

s2.displayCount()

Difference between class variable and instance variable


• 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
Example for instance attribute
class Rectangle:
def __init__(self, height, width):
self. height = height # instance variable
self. width = width

def area(self):
return self.height * self.width

def perimeter(self):
return (self.height + self.width)*2

a = int(input("Enter height of rectangle: "))


b = int(input("Enter width of rectangle: "))

#Creating the object


obj = Rectangle(a, b)

y=obj.area() # function call using object


z=obj.perimeter() # function call using object

print('The area of rectangle:', y)


print('The Perimeter of rectangle:', z)

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Example for class attribute


class Rectangle:
width=15 #class attribute
def __init__(self, height, width):
self. height = height # instance variable

def area(self):
return self.height * self.width

def perimeter(self):
return (self.height + self.width)*2

h= int(input("Enter height of rectangle: "))

#Creating the object


obj = Rectangle(h)

y=obj.area() # function call using object


z=obj.perimeter() # function call using object

print('The area of rectangle:', y)


print('The Perimeter of rectangle:', z)

Explain single, multiple, multilevel and hierarchical inheritance


Inheritance :

• In inheritance, child class inherits properties of parent class.


• child class acquires the properties and can access all the data members and functions defined in the
parent class.
• It provides the reusability of a code. We don’t have to write the same code again and again.
#Parent class
class Parent_Solve:
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
# Child class inheriting from the Solve class

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

class Child_Solve(Parent_Solve):
def multiply(self):
z = self.a * self.b
return z

# Creating an object of the child class


obj = Child_Solve(10.0, 20.0)

# 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)

# Calling the multiply method of the child class


Result2 = obj.multiply()
print("Product:", product_result)

Multiple Inheritance: Inheriting from multiple parents


Hierarchical Inheritance: Multiple children from same parents

# 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")

# Multiple inheritance : Child 1 inheriting from Parent 1 and Parent 2


class Child1(Parent1, Parent2):
def method3(self):
print("This is method 3 from Child 1")

# Heirachical ; Child 2 and child3 are inheriting from same Parent 1


class Child2(Parent1):
def method4(self):
print("This is method 4 from Child 2")

class Child3(Parent1):
def method5(self):
print("This is method 5 from Child 3")

# Creating an object of Child 1 class


child1 = Child1()
child1.method1() # Method from Parent 1

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

child1.method2() # Method from Parent 2


child1.method3() # Method from Child 1

# Creating an object of Child 2 class


child2 = Child2()
child2.method1() # Method from Parent 1
child2.method4() # Method from Child 2

# Creating an object of Child 3 class


child3 = Child3()
child3.method1() # Method from Parent 1
child3.method5() # Method from Child 3

Or you can give below example

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

# Creating an object of the Child class


obj = Child1(10, 20)

# By using child class object, call the function of parent class & child class

# Calling method from the parent class

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Y1 = obj.add()
print(Y1)

# Calling the div method of the child class


Y2 = obj.div()
print(Y2)

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

# Inheriting from multiple classes


class Child1(Parent1, Parent2):
def div(self):
y = self.a / self.b
return y

# Creating an object of the Child class


obj = Child1(10, 20)

# 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()

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

print(Y1)

# Calling the method from Parent2 class


Y2 = obj.mul()
print(Y2)

# Calling the method from the child class


Y3 = obj.div()
print(Y3)

#multi-level inheritance
In multi-level inheritance, a derived(child) class inherits from another derived (child) class

# 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

# Inheriting from Parent1


class Child1(Parent1):
def div(self):
y = self.a / self.b
return y

# Inheriting from Child1


class Child2(Child1, Parent2):
def sub(self):
y = self.a - self.b
return y

# Creating an object of the Child2 class


obj = Child2(10, 20)

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

# By using Child2 object, we can call the function of parent class & child class
# Calling method from Parent1 class
Y1 = obj.add()
print(Y1)

# Calling the method from Parent2 class


Y2 = obj.mul()
print(Y2)

# Calling the method from Child1 class


Y3 = obj.div()
print(Y3)

# Calling the method from Child2 class


Y4 = obj.sub()
print(Y4)

Prototyping v/s Planning

Prototype and Patch


• Whenever if we do not have the deep understanding of the complete problem statement, in
this case, first we have to write the basic prototype or program with available information.
• Then modify the program incrementally as and when we get more information about problem
statement and then patch (correct) the errors. This methodology is known as prototype and
patch.
Example: Start by basic Time class with available information.
class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second

def add_time(self, t2):


sum_hour = self.hour + t2.hour
sum_minute = self.minute + t2.minute
sum_second = self.second + t2.second
return Time(sum_hour, sum_minute, sum_second)

def display_time(self):
print(f'{self.hour:02d}:{self.minute:02d}:{self.second:02d}')

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Modifying the Prototype:


• To handle overflow and all possible inputs, we can modify the program

class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second

def add_time(self, t2):


sum_hour = self.hour + t2.hour
sum_minute = self.minute + t2.minute
sum_second = self.second + t2.second

# Handling overflow in seconds and minutes


if sum_second >= 60:
sum_second -= 60
sum_minute += 1

if sum_minute >= 60:


sum_minute -= 60
sum_hour += 1

return Time(sum_hour, sum_minute, sum_second)

def display_time(self):
print(f'{self.hour:02d}:{self.minute:02d}:{self.second:02d}')

# Creating time objects and adding them


t1 = Time(2, 10, 50)
t2 = Time(1, 20, 20)
t3 = t1.add_time(t2)

t1.display_time() # Output: 02:10:50


t2.display_time() # Output: 01:20:20
t3.display_time() # Output: 03:31:10

• 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:

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second

def add_time(self, t2):


# Sum hours, minutes, and seconds
sum_hour = self.hour + t2.hour
sum_minute = self.minute + t2.minute
sum_second = self.second + t2.second

# Handle overflow of seconds into minutes


while sum_second >= 60:
sum_second -= 60
sum_minute += 1

# Handle overflow of minutes into hours


while sum_minute >= 60:
sum_minute -= 60
sum_hour += 1

# Return a new Time object with the summed values


return Time(sum_hour, sum_minute, sum_second)

def display_time(self):

print(f'{self.hour:02d}:{self.minute:02d}:{self.second:02d}')

# Creating time objects and adding them


t1 = Time(2, 10, 50)
t2 = Time(1, 20, 20)
t3 = t1.add_time(t2)

t1.display_time() # Output: 02:10:50


t2.display_time() # Output: 01:20:20
t3.display_time() # Output: 03:31:10

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.

Explain Objects are mutable


o Objects in Python are mutable, it means, state of object can be changed, even after they are
created by assigning new values to their attributes
o Example 1: Changing Object value
o In the case of a Rectangle object (rect), you can change its size by modifying its width and
height attributes:

rect.width = rect.width + 50
rect.height = rect.height + 100

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

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}')

# Creating a Time object


time_obj = Time(9, 5, 45)

# Printing the time in hour:minute:second format


print_time(time_obj)

Prof. Sujay Gejji ECE, SGBIT, Belagavi

You might also like