0% found this document useful (0 votes)
18 views8 pages

Class Space

The document explains fundamental concepts of Python programming, including classes, objects, attributes, mutability, and operator overloading. It provides examples of defining classes, creating objects, and using methods such as copy and print. Additionally, it discusses special methods like __init__ and __str__, and demonstrates how to handle complex numbers and student score calculations.

Uploaded by

Siddaraju S
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)
18 views8 pages

Class Space

The document explains fundamental concepts of Python programming, including classes, objects, attributes, mutability, and operator overloading. It provides examples of defining classes, creating objects, and using methods such as copy and print. Additionally, it discusses special methods like __init__ and __str__, and demonstrates how to handle complex numbers and student score calculations.

Uploaded by

Siddaraju S
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
You are on page 1/ 8

1. What is class, object, attributes?

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:

class Point (object):


Represents a point in 2-D space !

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.

2. How objects are mutable? Justify with an example.


The mutability of objects means we can change the state of an object by making an
assignment to one of its attributes. For example, consider the following

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

class Point (object):


Represents a point in 2-D space
pl = Point ()
=
pl.x 3.0
=
pl.y 4.0
import copy
p2 = copy. copy (p1)

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

class Time (object):


Represents the time of the day

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

The output of this code will be 09:30:30.


5. Briefly explain the printing of objects with an example.
Note: The answer to the previous question may also be used here. Another example is
below.
In the following example a Point class is created. An object of Point class is created and
given the x and y attributes. The function print_point prints out the x and y coordinates
of a Point object pl.
class Point (object):
I Represents a point in 2-D space

:
def print_point (p)
print ( f'({p. x}, (p.y}) ')

pl = Point ()
pl.x = 3
= 4
pl.y
print_point (p1)

The output of this code will be (3,4).

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

def find _center (rect):


p = Point ()
p.x = rect.corner.x + rect.width/2
p.y =
rect.corner. t y
rect.height/2
return p

=
center find _center (box)
print__point (center)

The output of the above code will be (50, 100).


7. Demonstrate pure functions and modifiers with examples.
A pure function 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. Consider
the following example.
:
def add_time (tl, t2)
sum = Time ()
sum.hour = tl.hur + t2.hour

sum.minute = tl. minute + t2.minute


sum. second = t1. second + t2.second
return sum

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

if time.second >= 60:


time. second -= 60
time.minute t= 1

if time.minute >= 60:


time.minute -= 60
time. hour t= 1

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.

8. Explain operator overloading and polymorphism with examples.


In Python a programmer can define special methods which start with double under
scores(--) and end with the same. By defining special methods, the normal behaviour
of operators can be changed. This is called operator overloading in Python. The add
method defined in the following code redefines the action of the +' operator to operate
on Time objects.

class Time (object):


Represents the time of day

:
def add (self, other)
seconds = self.time_to_int () + other.time_to_int ()
return int_to_time (seconds)

Following code shows the effect

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

def init hour=0,


(self, minute=0, second=0):
self. hour =
hour
self. minute = minute
self.second = second

The benefit of -init_ method is that the variables may be initiated at the time of creation
of the objects as shown below

tl = Time (9, 45)

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.

class Time (object):


Represents the time of the day

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.

tl = Time (9, 45)


print (t1)

The output of this code will be 09:45: 00.


10. Definea function which takes TW0 objects representing complex numbers and re
turns new complexX number with a addition of two complex numbers. Define a suit
able class Complex to represent the complex number. Develop a program to read
N(N>=2) complex numbers and to compute the addition of complex numbers. N

class complex:
rpart=0.0
ipart=0.0

def add (self, comp):


self.rpart=self.rparttcomp. rpart
self.ipart=self. iparttcomp. ipart

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)

print ("Final result {0} + i {1):".format (res.rpart, res. ipart) )

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

def _init_(self, name, usn, marks):

6
self.stu_name=usn
self. usn=usn
self.marks_list=marks

def getMarks (self):


print ("Enter marks of three subject:\n" )

marks1=int (input ("Enter marks of 1st subject\n") )

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 display (self):


print ("total marks=", self.marks_list[3])
print ("Percentage=", (self.marks_list [3] ) * (100/300) )

name=input ("Enter student name\n")


usn=input ("Enter student usn\n")
st =
student (name, usn, [])
st.getMarks ()
st.display ()

12. Discuss Type based dispatch in Python.


Sometimes it is required to do operations on two different types of objects, for example
a Time object and an integer object. Then it is required to check the type of the objects
passed on to a function so that no error gets generated. The following code checks the
type of other and invokes either add\time or increment functions:

# inside class Time:

def _add (self, other):


:
if isinstance (other, Time)
return self.add time (other)
else:
return self.increment (other)

def add_time (self, other):


seconds = self.time_to_int () + other.time_to_int ()
return int_to_time (seconds)

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy