Application Development using Python (18CS55) VTU Questions and Solutions - 3
1. What is class, object. Explain copy.copy() with an example code.
A class is a
user-defined blueprint or prototype from which objects are created. 2Marks
An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values.
Copying an object is often an alternative to aliasing. The copy module contains a function
called copy that can duplicate any object:
p1 = Point()
p1.x = 3.0
p1.y = 4.0
import copy
p2 = copy.copy(p1)
p1 and p2 contain the same data, but they are not the same Point.
print_point(p1)
(3, 4)
print_point(p2)
(3, 4)
p1 is p2
False
2. Demonstrate pure functions and modifiers with example codes
A pure function because it does not modify any of
the objects passed to it as arguments and it has no effect, like displaying a
value or getting user input, other than returning a value.
Example code (3 Marks)
sum = Time()
sum.hour = t1.hour + t2.hour
sum.minute = t1.minute + t2.minute
sum.second = t1.second + t2.second
return sum
Sometimes it is useful for a
function to modify the objects it gets as parameters. In that case, the changes
are visible to the caller. Functions that work this way are called modifiers
Example code (3Marks)
def add_time(t1, t2):
sum = Time()
sum.hour = t1.hour + t2.hour
sum.minute = t1.minute + t2.minute
sum.second = t1.second + t2.second
if sum.second >= 60:
sum.second -= 60
sum.minute += 1
if sum.minute >= 60:
sum.minute -= 60
sum.hour += 1
return sum
3. Explain Instance attributes and class attributes with an example code.
Class attributes: Common for all objects (2Marks)
class Point:
x=0
Instance attribute: Only for specifies instance (2Marks)
class Point:
define __init__(self,x):
self.x=x
4. Consider a user defined class called Time that records the time of the day. Create a new Time object and assign attributes for hours, minutes and seconds. Write a function called print_time that takes a Time object and prints it in the form hour:minute:second. Write a Boolean function called is_after that takes two Time objects, t1 and t2, and returns True if t1 follows t2 chronologically and False otherwise.
from __future__ import print_function, division
class Time:
"""Represents
the time of day.
attributes: hour, minute,
second
"""
def __init__(self, hour=0,
minute=0, second=0):
"""Initializes a time object.
hour: int
minute: int
second: int or float
"""
self.hour = hour
self.minute = minute
self.second = second
def __str__(self):
"""Returns a
string representation of the time."""
return '%.2d:%.2d:%.2d' %
(self.hour, self.minute, self.second)
def print_time(self):
"""Prints a
string representation of the time."""
print(str(self))
def time_to_int(self):
"""Computes
the number of seconds since midnight."""
minutes = self.hour * 60 +
self.minute
seconds = minutes * 60 +
self.second
return seconds
def is_after(self, other):
"""Returns
True if t1 is after t2; false otherwise."""
return self.time_to_int()
> other.time_to_int()
def main():
start = Time(9, 45, 00)
start.print_time()
end = Time(9,50,2)
end.print_time()
print('Is end after start?')
print(end.is_after(start))
if __name__ == '__main__':
main()
5. Explain operator overloading with an example code to overload “+” and “-” operators by providing the methods __add__ and __sub__.
By defining
other special methods, you can specify the behavior of operators on programmer-defined
types. For example, if you define a method named __add__ for the Time class,
you can use the + operator on Time objects.
# inside class
Time:
def
__add__(self, other):
2M
seconds = self.time_to_int() + other.time_to_int()
return int_to_time(seconds)
def __sub__(self,
other):
2M
seconds = self.time_to_int() -
other.time_to_int()
return int_to_time(seconds)
start = Time(9,
45)
duration = Time(1,
35)
print(start +
duration)
print(start -
duration)
6. Write a python program that has a class Point with attributes as X and Y co-ordinates.
Create two objects of this class and find the midpoint of both the points. Add
a method
reflex_x to class point, which returns a new point.
Sample
output: P1(10,10)
P2(20,20)
Midpoint(15,15)
pointx(10,10)
Reflex_pointx(10,-10)
class Point:
def __init__(self,x=0.0,y=0.0):
self.x=x
self.y=y
def __str__(self):
return
"Point({},{})".format(str(self.x),str(self.y))
def Midpoint(self,other):
P3 = Point()
P3.x=(self.x+other.x)/2
P3.y=(self.y+other.y)/2
return P3
def Reflex_pointx(self):
P=Point()
P.x=self.x
P.y=-self.y
return P
P1=Point(10,10)
P2=Point(20,20)
print(P1)
print(P2)
P3=Point()
P3=P1.Midpoint(P2)
print(P3)
P3=P1.Reflex_pointx()
The init method (short for
“initialization”) is a special method that gets invoked when an object is
instantiated. Its full name is __init__ (two underscore characters,
followed by init, and then two
more underscores). An init method for the Time class might look like this:
# inside class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
__str__ is a special method, like __init__, that is supposed to return a
string representation of an object.
For example, here is a str method for Time objects:
# inside class Time:
def __str__(self):
return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)
When you print an object, Python invokes the str method:
time = Time(9, 45)
print(time)
09:45:00
8. Write a pythonic code to create a function named move_rectangle that takes an object Rectangle and two numbers named dx and dy. It should change the location of the Rectangle by adding dx to the x coordinate of corner and adding dy to the y coordinate of corner.
class Point:
def
__init__(self,x=0,y=0):
self.x=x
self.y=y
def
__str__(self):
return
'(%g, %g)' % (self.x, self.y)
class Rectangle:
def
__init__(self,x=0,y=0):
self.corner=Point(x,y)
print(self.corner)
def move_rectangle(box,dx,dy):
box.corner.x+=dx
box.corner.y+=dy
print(box.corner)
def main():
box=Rectangle(10,10)
move_rectangle(box,20,20)
if __name__ == '__main__':
Polymorphism
means multiple forms. In python we can find the same operator or function taking
multiple forms. It also useful in creating different classes which will have
class methods with same name. That helps in re using a lot of code and
decreases code complexity. 3Marks
def histogram(s): 7Marks
d = {}
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
word=histogram("hello")
print(word)
sentence=histogram("Polymorphism example is here")
print(sentence)
10.
Differentiate between single, multiple and multi-level
inheritance.
Write a program that has a class Person, inherit a
class Student from Person which also has a class MarksAttendance.
Assume the attributes for Person class as: USN, Name, DoB, gender. Attributes
for Student class as: Class, branch, year, MA. (note:MA is an object of
class MarksAttendance)
Attributes for MarksAttendance: Marks,
Attendance.
Create 10 student objects and display all the details of the student whose
marks is less than 40 including information inherited from other class.
Single inheritance: When a child class inherits from
only one parent class, it is called single inheritance.
Multilevel Inheritance:
In multilevel inheritance, we inherit the classes at
multiple separate levels. We have three classes A, B and C, where A is the
super class, B is its sub(child) class and C is the sub class of B.
Multiple Inheritance:
Multiple Inheritance means that you're inheriting the
property of multiple classes into one. In case you have two classes, say A and
B, and you want to create a new class which inherits the properties of both A
and B. 3Marks
class Person():
7Marks
def
__init__(self,usn='',name='',dob='',gender=''):
self.usn=usn
self.name=name
self.dob=dob
self.gender=gender
def
__str__(self):
return
self.usn+' '+self.name+' '+self.dob+' '+self.gender
class Student(Person):
def
__init__(self,usn='',name='',dob='',gender='',branch='', year='', ma=''):
super().__init__(usn,name,dob,gender)
self.branch=branch
self.year=year
self.ma=ma
def
__str__(self):
return
super().__str__()+' '+ self.branch +' '+str(self.year)+' '+self.ma.__str__()
class MarksAttendance:
def
__init__(self,marks='',attend=''):
self.marks=marks
self.attend=attend
def
__str__(self):
return
str(self.marks)+' '+str(self.attend)
def main():
ma=[]
s=[]
for i in
range(2):
print(" enter "+str((i+1))+" Student information")
print("marks")
marks=int(input())
print("attendance")
attend=int(input())
ma1=MarksAttendance(marks,attend)
ma.append(ma1)
print("USN")
usn=input()
print("Name")
name=input()
print("DOB")
dob=input()
print("Gender")
gender=input()
print("Branch")
branch=input()
print("year")
year=int(input())
s1=Student(usn,name,dob,gender,branch,year,ma[i])
s.append(s1)
for i in s:
if
i.ma.marks < 40:
print(i)
if __name__=='__main__':
main()
11. Create a solution for calculating total marks and rank of the students in class by using python program. Consider an excel sheet “marks.xlsx” having fields Roll. No and 3 subjects marks as shown Figure 1. Create an output “marks.xlsx” as shown in Figure 2 by calculating Total of 3 subjects and Rank based on the Total marks.
import openpyxl
from openpyxl import Workbook
ma=openpyxl.load_workbook('marks.xlsx')
masheet=ma['Sheet1']
top=[]
masheet.cell(row=1,column=5).value='Total'
for r in range(2,9):
s=0
for j in range(2,5):
s=s+masheet.cell(row=r,column=j).value
top.append(s)
masheet.cell(row=r,column=5).value=s
rank=0
masheet.cell(row=1,column=6).value='Rank'
for i in range(len(top)):
rank=1
for j in range(len(top)):
if (top[i]<top[j]):
if top[j] not in top[:j]:
rank=rank+1
masheet.cell(row=i+2,column=6).value=rank
ma.save('marks.xlsx')
Comments
Post a Comment