Class Space
Class Space
A class in Python is a type which can be defined by the programmer. A class is a template
for creating objects. A class can store data of different types. A python class is created
using the keyword class as follows:
An object is an instance of a class. For example, if dogs is a class the different breeds
of dogs like Labrador, German Shepherd etc are instances of the dogs class. All objects
of a particular class share some common attributes. Consider the Point class defined
above. An object of this class is created as follows:
blank = Point ()
The object blank is an instance of the class Point which can have a particular value
such as (0,0) or (2,3).
The attributes are particular characteristics of objects. For example, a member of the
dogs class can have a particular colour, height, style of barking etc. The colour, height
etc are called attributes. In the Point class example, the attributes of the object blank
can be stated as
= 0
blank.x
blank.y = 0
The object blank has x and y coordinates with particular values as its attributes.
:
class Rectangle (object)
Represents a rectangle !
=
box Rectangle ()
box.width = 50
box. height = 40
To change the size of a rectangle without changing its position, we can modify the values
of width and height as
box.width = box.width + 50
box.height = box.height + 100
This will alter the width and height of the box object to 100 and 140 respectively.
3. Explain copy.copy with an example.
The copy.copy () method belongs to the copy module. It is used to copy objects
along with all the attributes. Consider the following example.
Here the copy () method of the module copy has copied all the attributes of the object
pl to another object p2. The objects pl and p2 are different but have the same data.
The drawback of the copy () method is that it does shallow copying. To copy all the
embedded objects the deepcopy () method should be used.
4. Write a function called print_time that takes a time object and print it in the form
hour:minutes:second
The following code shows the implementation of the function print _time. It takes a Time
object and prints it in the form hour:minutes:second format
:
def print_time (time)
%
print (%.2d:%.2d:%.2d' (time. hour,\
)
time.minute, time.second)
t1 = Time ()
t1.hour = 9
t1.minute = 30
t1.second = 30
print_time (tl)
:
def print_point (p)
print ( f'({p. x}, (p.y}) ')
pl = Point ()
pl.x = 3
= 4
pl.y
print_point (p1)
6. Define class and object, construct the class called rectangle and initialise it with
height=100, width = 200, starting point as (x=0, y=0). Write a program to display
the centrepoint coordinates of a rectangle.
Note: For class and object definitions refer above.
class Rectangle:
"n "Represents a rectangle.
attributes: width, height, corner.
box = Rectangle ()
=
box.width 100.0
=
box.height 200.0
box.corner = Point ()
box.Corner.x = 0.0
box.COrner.y = 0.0
=
center find _center (box)
print__point (center)
Here the function add time creates a new Time object, initializes its attributes, and
returns a reference to the new object.
If a function modifies the objects that it gets as parameters, then such a function is called
a modifier function. Consider the following example.
:
def increment (time, seconds)
time. second += seconds
Here the the parameter seconds is added to the time object based on some conditions.
We see that the time object got modified in this function and hence it is a modifier
function.
:
def add (self, other)
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)
This code would have given an error under normal circumstances. Here, since the be
haviour of the + operator is redefined in the class Time, it will return an answer.
Polymorphism is a basic tenet of any object oriented programming language along with
abstraction, encapsulation and inheritance. It helps code reuse. When a function can
work with several types, it is called polymorphic. For example, the built-in function sum,
which add the elements of a sequence, works as long as the elements of the sequence
support addition. Hence the function sum is polymorphic. Let's assume a Time class
which provides addition of Time objects via a special method -add_ We can add Time
objects using the sum function as below.
=
tl Time (7, 43)
t2 = Time (7, 41)
t3 = Time (7, 37)
= sum( [tl,t2, t3])
total
print (total)
The above code prints the total time after adding individual Time objects.
9. Briefly discuss the init_ and str.
methods in Python.
The init method 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 nmethod for the Time class may be written as
:
class Time (object)
Represents the time of the day
The benefit of -init_ method is that the variables may be initiated at the time of creation
of the objects as shown below
Here the first value inside the parentheses is automatically assigned to the hour variable
and the second to the minute variable. Since the third value is not supplied, the second
variable will take the default value of 0.
The -str isa special method, like init-, that is supposed to return a string represen
tation of an object. Consider the following example.
def_str(self):
return %.2d:%.2d:%.2d' %
(self.hour, \
self.minute, self.second)
5
When we invoke the print() function on a Time object Python will print the time in
the format available in the str method.
class complex:
rpart=0.0
ipart=0.0
res=complex ()
n=int (input ("Enter number of complex numbers to add: \n"))
for i in range (1, n+1) :
rpart=float (input ("Enter real part of complex number \
{0}:".format (i)))
ipartfloat (input ("Enter imaginary part of complex number \
{0}:". format (i) ))
comp=complex ()
comp.rpart=rpart
comp. ipart-ipart
res.add (comp)
11. Develop a program that uses class Student which prompts the user to enter marks
in three subjects and calculates total marks, percentage and displays the score card
details.Use list to store the marks in three subjects and total marks. Use init_0
method to initialize name, USN and the lists to store markS and total, Use get
Marks() method to read marks into the list, and display0 method to display the
score card details.
class student:
stu_name=
Usne"n
marks_list=list ()
6
self.stu_name=usn
self. usn=usn
self.marks_list=marks
self.marks_list.append (marksl)
marks2=int (input ("Enter marks of 2nd subject\n") )
self.marks_list.append (marks2)
marks3=int (input ("Enter marks of 3rd subject\n"))
self.marks_list.append (marks3)
self.marks_list.append (sum (self.marks_list) )
:
def increment (self, seconds)
seconds += self.time_tO_int ()
return int_to_time (seconds)
7
The built-in function isinstance takes a value and a class object, and returns True
if the value is an instance of the class. If other is a Time object, -_add_ invokes
add_time. Otherwise it assumes that the parameter is a number and invokes increment.
This operation is called a type-based dispatch because it dispatches the computation to
different methods based on the type of the arguments.