0% found this document useful (0 votes)
2 views

python_module5_finalerherh

The document provides an overview of classes and objects in Python, emphasizing the distinction between user-defined classes and built-in types. It explains how to create classes, instantiate objects, and manage attributes, including instance and class attributes. Additionally, it covers concepts such as object mutability, copying objects, and the use of shallow and deep copies in Python.

Uploaded by

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

python_module5_finalerherh

The document provides an overview of classes and objects in Python, emphasizing the distinction between user-defined classes and built-in types. It explains how to create classes, instantiate objects, and manage attributes, including instance and class attributes. Additionally, it covers concepts such as object mutability, copying objects, and the use of shallow and deep copies in Python.

Uploaded by

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

1 March 2025 1

CLASS:
CLASSES AND OBJECTS
1. Python is an object-oriented programming language
2. Class is a user-defined data type which binds data and functions together
into single entity.
3. Class is just a prototype (or a logical entity/blue print) which will not
consume any memory
4. A class can have a set of variables (also known as attributes, member
variables) and member functions (also known as methods).

OBJECT:
1. An object is an instance of a class and it has physical existence (Memory).
2. One can create any number of objects for a class

1 March 2025 2
Programmer-defined Types
We have used many of Python’s built-in types; now we are going to define a
new type. As an example, we will create a type called Point that represents a
point in two-dimensional space

In mathematical notation, points are often written in parentheses with a


comma separating the coordinates. For example, (0, 0) represents the
origin, and (x, y) represents the point x units to the right and y units up
from the origin.

1 March 2025 3
There are several ways we might represent points in Python:

• We could store the coordinates separately in two variables, x and y.


• We could store the coordinates as elements in a list or tuple.
• We could create a new type to represent points as objects

A programmer-defined type is also called a class. A class definition looks like


this:
class Point:
"""Represents a point in 2-D space."""

1 March 2025 4
Creating empty class using keyword class
• A class in Python can be created using a keyword class. Here, we are creating an empty
class without any members by just using the keyword pass within it.
• Create user define data type using class keyword
Now, a user-defined data type Point got
class Point: created, and this can be used to create any
pass number of objects of this class. Observe
the following statements –

blank=Point()
The process of creating a new object is
print(blank)
called as instance of a class. When we
print an object, Python tells which
The output would be – class it belongs to and where it is
< main .Point object at 0x003C1BF0> stored in the memory.

1 March 2025 5
Instant Attributes of object
• An object can contain named elements known as attributes. One can assign values to
these attributes using dot operator.
• For example, keeping coordinate points in mind, we can assign two
attributes x and y for the object blank of a class Point as below –
• blank.x =10.0
• blank.y =20.0
• Thus, x and y are instance attributes
• but not class attributes.
NOTE:
>>> x= p.x
>>> print(x)
10.0
Here, the variable x is nothing to do with attribute p.x. There will not be any name conflict
between normal program variable and attributes of an object.
1 March 2025 6
Example:
class Point:
output
pass
blank object values are 10 20
blank=Point() the normal variable of x is 15
blank.x=10
blank.y=20
Here, the variable x is nothing to do
print( blank object values are ,blank.x,blank.y )
with attribute p.x. There will not be any
name conflict between normal
x=blank.x + 5;
program variable and attributes of an
print( the normal variable of x is ,x)
object.

1 March 2025 7
instance attributes AND class attributes
• User-defined classes in Python have two types of attributes viz. class attributes and instance
attributes. Class attributes are defined inside the class (usually, immediately after class header). They
are common to all the objects of that class. That is, they are shared by all the objects created from
that class. But, instance attributes defined for individual objects. They are available only for that
instance (or object). Attributes of one instance are not available for another instance of the same class.
For example, consider the class Point as discussed earlier –
• Instance Attribute example:
This clearly indicates that the attributes x and y
created are available only for the object p1, but not
class Point: for p2. Thus, x and y are instance attributes but not
pass class attributes.

p1
p1= Point() #first object of the class point
p1.x=10.0 #attributes for p1 x=10
p1.y=20.0 y=20
print(p1.x, p1.y) #prints 10.0 20.0
point p2
p2= Point() #second object of the class
print(p2.x) #displays error as below

AttributeError: Point object has no attribute x


1 March 2025 8
We will discuss class attributes late in-detail But, for the understanding purpose, observe the following
example –

• class Point: Here, the attributes x and y are defined inside the
definition of the class Point itself. Hence, they are
• x=2 available to all the objects of that class.
• y=3
p1
point
• p1=Point() #first object x=2
x=2 y=3
of the class y=3
• print(p1.x, p1.y) # prints 2 3 x=2
• y=3
• p2=Point() #second p2
object of the class
• print(p2.x, p2.y) # prints 2 3
1 March 2025 9
Example
• Write a class Point representing a point on coordinate system Implement
following functions –
 A function read_point() to receive x and y attributes of a Point object as user
input.
 A function distance() which takes two objects of Point class as arguments
and computes the Euclidean distance between them.
 A function print_point() to display one point in the form of ordered-pair.

• As we know, the Euclidean distance between two points (x1,y1) and (x2,y2) is

1 March 2025 10
import math p1=Point() #create first object
class Point: print("Enter First point:")
pass read_point(p1) #read x and y for p1

def read_point(p): p2=Point() #create second object p1


Alias
p.x=float(input("x coordinate:")) print("Enter Second point:")
variable
p.y=float(input("y coordinate:")) read_point(p2) #read x and y for p2

def print_point(p): dist=distance(p1,p2) #compute distance x=10


p
print("(%g,%g)"%(p.x, p.y)) y=20
print("First point is:")
def distance(p1,p2): print_point(p1) #print p1
d=math.sqrt((p1.x-p2.x)**2+(p1.y-p2.y)**2) print("Second point is:") p2
return d print_point(p2) #print p2
print("Distance is: %g" %(distance(p1,p2)))

The sample output of above program would be – x=3


Enter First point: p
y=5
x coordinate: 10 y coordinate : 20
Enter Second point:
x coordinate: 3 y coordinate:5
First point is: (10,20)
Second point is:(3,5) Distance is: 16.5529
1 March 2025 11
Rectangles
• It is possible to make an object of one class as an attribute to other
class. To illustrate this,
• Write a class Rectangle containing numeric attributes width and
height. This class should contain another attribute corner which is an
instance of another class Point.
• Implement following functions –
• · A function to print corner or center point as an ordered-pair
• · A function find_center() to compute center point of the rectangle
• · A function resize() or grow() to modify the size of rectangle

1 March 2025 12
class Point: box=Rectangle() #create Rectangle object
Pass box.corner=Point() #define an attribute corner for box
box.width=100 #set attribute width to box
box.height=200 #set attribute height to box
class Rectangle:
box.corner.x=0 #corner itself has two attributes x and y
Pass
box.corner.y=0 #initialize x and y to 0

def find_center(rect): print("Original Rectangle is:")


p=Point() print("width=%g, height=%g"%(box.width, box.height))
p.x = rect.corner.x + rect.width/2
p.y = rect.corner.y + rect.height/2 center=find_center(box) A sample output would be:
return p Original Rectangle is: width=100, height=200
The center of rectangle is: (50,100)
print("The center of rectangle is:")
Rectangle after resize: width=150, height=270
print_point(center)
def resize(rect, w, h): The center of resized rectangle is: (75,135)

rect.width +=w
resize(box,50,70)
rect.height +=h print("Rectangle after resize:")
print("width=%g, height=%g"%(box.width, box.height))
def print_point(p):
print("(%g,%g)” %(p.x, p.y)) center=find_center(box)
print("The center of resized rectangle is:")
print_point(center)
1 March 2025 13
Instances as return values
Functions can return instances. For example, find_center takes a Rectangle
as an argument and returns a Point that contains the coordinates of the
center of the Rectangle:
def find_center(rect):
p = Point()
p.x = rect.corner.x + rect.width/2
p.y = rect.corner.y + rect.height/2
return p

center = find_center(box)
print_point(center)

1 March 2025 14
Objects are mutable
You can change the state of an object by making an assignment to one of its attributes.
For example, to change the size of a rectangle without changing its position, you can
modify the values of width and height:
box.width = box.width + 50
box.height = box.height + 100
You can also write functions that modify objects. For example, grow_rectangle takes a
Rectangle object and two numbers, dwidth and dheight, and adds the numbers to the
width and height of the rectangle Here is an example that demonstrates the effect:
def grow_rectangle(rect, dwidth, dheight): >>> box.width, box.height
(150.0, 300.0)
rect.width += dwidth
>>> grow_rectangle(box, 50, 100)
rect.height += dheight >>> box.width, box.height
(200.0, 400.0)
1 March 2025 15
Copying FROM one Object to another Object
An object will be aliased whenever there an object is assigned to . Let us understand the concept of aliasing more in
another object of same class. This may happen in following detail using the following program –
situations – >>> class Point:
· Direct object assignment (like p2=p1) pass
· When an object is passed as an argument to a function
· When an object is returned from a function >>> p1=Point()
>>> p1.x=10
>>> p1.y=20
>>> p2=p1
>>> print(p1)
< main .Point object at 0x01581BF0>
Hence, if we check for equality and identity of these two >>> print(p2)
objects, we will get following result. < main .Point object at 0x01581BF0>
>>>Print(p1.x, p1.y) // x=10. y=20
>>> p1 is p2 >>>print(p2.x,p2.y) //x=10, y=20
True
>>> p1==p2 Observe that both p1 and p2 objects have same
True physical memory. It is clear now that the object p2 is
an alias for p1. So, we can draw the object diagram
1 March 2025 16
Note:

But, the aliasing is not good always. For example, we may need to create a new
object using an existing object such that – the new object should have a different physical memory, but it
must have same attribute (and their values) as that of existing object. Diagrammatically, we need something
as below –

In short, we need a copy of an object, but not an alias. To do this, Python provides
a module called copy and a method called copy().

1 March 2025 17
Consider the below given program to understand the concept.

>>> class Point:


pass Observe that the physical address of the objects p1 and
p2 are now different. But, values of attributes x and y are
>>> p1=Point() same. Now, use the following statements –
>>> p1.x=10
>>> p1.y=20 >>> p1 is p2
False
>>> import copy #import module copy >>> p1 == p2
>>> p2=copy copy(p1) #use the method copy() False
>>> print(p1)
< main .Point object at 0x01581BF0> Here, the is operator gives the result as False for the obvious reason of
>>> print(p2) p1 and p2 are being two different entities on the memory. But, why ==
operator is generating False as the result, though the contents of two
< main .Point object at 0x02344A50> objects are same? The reason is – p1 and p2 are the objects of user-
>>> print(p2.x,p2.y) defined type. And, Python cannot understand the meaning of equality on
10 20 the new data type. The default behavior of equality (==) is identity (is
operator) itself. Hence, Python applies this default behavior on p1 == p2
and results in False.

1 March 2025 18
Example2:
The copy() method of copy module duplicates the object. The content (i.e. attributes) of one object is copied into another
object as we have discussed till now. But, when an object itself is an attribute inside another object, the duplication will
result in a strange manner. To understand this concept, try to copy Rectangle object (created in previous section) as given
below –
Whenever the statement
import copy
class Point: box2=copy.copy(box1)
pass
class Rectangle:
Pass

box1=Rectangle()
box1.corner=Point()
Thus, the physical object to which box1.corner and
box1.width=100
box2.corner are pointing is only one. This type of copying
box1.height=200
the objects is known as shallow copy.
box1.corner.x=0
box1.corner.y=0
box2=copy copy(box1)
print(box1 is box2) #prints False
print(box1 corner is box2 corner) #prints True
1 March 2025 19
Note: deepcopy() function
Now, the attributes width and height for two objects box1 and box2 are independent. Whereas, the
attribute corner is shared by both the objects. Thus, any modification done to box1.corner will reflect
box2.corner as well. Obviously, we don’t want this to happen, whenever we create duplicate objects.
That is, we want two independent physical objects. Python provides a method deepcopy() for doing
this task. This method copies not only the object but also the objects it refers to, and the objects they
refer to, and so on.

box3=copy.deepcopy(box1)
print(box1 is box3) #prints False
print(box1.corner is box3.corner) #prints False

Thus, the objects box1 and box3 are now completely independent.

1 March 2025 20
CLASSES AND FUNCTIONS
Now that we know how to create new types, the next step is to write functions
that take programmer-defined objects as parameters and return them as
results.
• Python is object oriented programming languages, it is possible to use it as
functional programming There are two types of functions viz. pure functions and
modifiers function.
• pure functions:
• A pure function takes objects as arguments and does some work without
modifying any of the original argument.
• Modifiers function
• the name suggests, modifier function modifies the original argument.

1 March 2025 21
Time class
Example of a programmer-defined type, we’ll define a class called Time that records the
time of day.
The class definition looks like this:
class Time: The state diagram for the Time object looks like
pass

time = Time() # We can create a new Time object and assign


attributes for hours, minutes, and seconds:
time.hour = 11
time.minute = 59
time.second = 30

1 March 2025 22
Pure function example: Time
Creating a class called Time. An object of class Time contains hour,
minutes and seconds as attributes. Write a function to print time in
HH:MM:SS format and another function to add two time objects.

Note that, adding two time objects should yield proper result
and hence we need to check whether number of seconds
exceeds 60, minutes exceeds 60 etc, and take appropriate
action.

1 March 2025 23
Pure fuction example
t1=Time()
class Time: t1.hour=10
Pass t1.minute=34
t1.second=25
def printTime(t): print("Time1 is:") printTime(t1)

print("%.2d:%.2d:%.2d"%(t.hour,t.minute,t.second)) t2=Time()
t2.hour=2
def add_time(t1,t2): t2.minute=12
sum=Time() t2.second=41
sum.hour = t1.hour + t2.hour print("Time2 is :") printTime(t2)
sum.minute = t1.minute + t2.minute
sum.second = t1.second + t2.second t3=add_time(t1,t2)
if sum.second >= 60: print("After adding two time objects:")
sum.second = sum.second -60 printTime(t3)
sum.minute = sum.minute +1
if sum.minute >= 60: The output of this program would be –
sum.minute = sum.minute - 60 Time1 is: 10:34:25
sum.hour = sum.hour+ 1 Time2 is : 02:12:41
return sum After adding two time objects: 12:47:06
1 March 2025 24
Modifiers
Sometimes, it is necessary to modify the underlying
argument so as to reflect the caller. That is, arguments
have to be modified inside a function and these
modifications should be available to the caller. The
functions that perform such modifications are known
as modifier function.

1 March 2025 25
Example:
Class Time:
pass Start
done
Start = Time()
Def increment(time, seconds):
Hour=9
time.second=time.second + seconds Start.hour =9
Hour=11
Minute=45
Minute=41
Start.minute=45 Second=40 Second=0
if time.second >= 60:
s = time.second/60 Start.second=0
time.second = time.second – int(s) * 60
time.minute = time.minute + int(s) seconds = 7000
Hour=9
Minute=45 time
if time.minute > 60 : done = increment(Start, seconds) Second=0
m = time.minute/60 Print_time(done)
time.minute = time.minute – int(m) * 60
time.hour = time.hour + int(m)
if time.hour > 12 : Output:
H:11 M:41 S:40 Hour=11
time.hour=time.hour-12 Minute=41 time
return time Second=40
def print_time(t):
print(‘H:” t.hour,’M:’t.minute,’S:’t.second)
1 March 2025 26
Prototyping versus planning
Whenever we do not know the complete problem statement, we may write the
program initially, and then keep of modifying it as and when requirement
(problem definition) changes. This methodology is known as prototype and
patch. That is, first design the prototype based on the information available
and then perform patch-work as and when extra information is gathered. But,
this type of incremental development may end-up in unnecessary code, with
many special cases and it may be unreliable too.

An alternative is designed development or plan development, in which


high-level insight into the problem can make the programming much easier.
For example, if we consider the problem of adding two time objects, adding
seconds to time object etc. as a problem involving numbers with base 60 (as
every hour is 60 minutes and every minute is 60 seconds)

1 March 2025 27
And here is the function that converts integers to Times (recall
that divmod divides the first argument by the second and
Here is a function that converts Times to integers:
returns the quotient and remainder as a tuple)

def time_to_int(time):
minutes = time.hour * 60 + time.minute def int_to_time(seconds):
seconds = minutes * 60 + time.second time = Time()
minutes, time.second = divmod(seconds, 60)
return seconds
time.hour, time.minute = divmod(minutes, 60)
return time

def add_time(t1, t2):


seconds = time_to_int(t1) + time_to_int(t2)
return int_to_time(seconds)

1 March 2025 28
CLASSES AND METHODS
The classes that have been considered till now were just
empty classes without having any definition. But, in a
true object oriented programming, a class contains
class-level attributes, instance-level attributes, methods
etc. There will be a tight relationship between the
object of the class and the function that operate on
those objects

1 March 2025 29
Object-Oriented Features
As an object oriented programming language, Python possess following
characteristics:
· Programs include class and method definitions.
· Most of the computation is expressed in terms of operations on objects.
· Objects often represent things in the real world, and methods often
correspond to the ways objects in the real world interact.

1 March 2025 30
WHAT IS A METHOD ?
A function which is associated with a particular class is known as a
method.

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

1 March 2025 31
Printing objects
Class and function Class and Method
class Time:
pass class Time:
def print_time(time):
print( %.2d:%.2d:%.2d % (time.hour, time.minute,
def print_time(time): time.second))
print( %.2d:%.2d:%.2d % (time.hour, time.minute, time.second))
start = Time()
start = Time() start.hour = 9
start.hour = 9 start.minute = 45
start.minute = 45 start.second = 00
start.second = 00 #first way to call class method
#To call this function, you have to pass a Time object as an argument Time print_time(start)
print_time(start) or
start print_time( )
output:

09:45:00
output: 09:45:00
1 March 2025 32
Another example
Keep in mind that every method of any class must have the first
argument as self. The argument self is a reference to the current
object. That is, it is reference to the object which invoked the
method. (Those who know C++, can relate self with this pointer).
The object which invokes a method is also known as subject.

1 March 2025 33
class Time: Start = Time()
def increment(self, seconds):
self.second=self.second + seconds Start.hour =9
Start.minute=45
if self.second >= 60 : Start.second=0
s = self.second/60
self.second = self.second - int(s)*60 seconds = 7000
self.minute = self.minute + int(s)
print(self.minute) Time.increment(Start,seconds)
Start.print_time( )
if self.minute > 60 :
m = self.minute/60
print(m)
self.minute = self.minute - int(m) * 60 output
self.hour = self.hour + int(m)
if self.hour > 12 :
self.hour=self.hour-12 161
return self 2.683333333333333
H: 11 M: 41 S: 40
def print_time(t):
print( H: ,t.hour, M: ,t.minute, S: ,t.second)

1 March 2025 34
The __init () Method
(Amethod init () has to be written with two underscores
before and after the word init)

Python provides a special called as __ init _() which is similar to


constructor method in other programming languages like
C++/Java. The term init indicates initialization. As the name
suggests, this method is invoked automatically when the object
of a class is created.
Consider the example given here –

1 March 2025 35
The __str__ method
The next method inside the class is __str__(). It is a special method used for string
representation of user-defined object. Usually, print() is used for printing basic types in
Python. But, user-defined types (class objects) have their own meaning and a way of representation.
To display such types, we can write functions or methods like print_point() but, more
polymorphic way is to use str () so that, when we write just print() in the main part of the
program, the str () method will be invoked automatically. Thus, when we use the statement
like –
print("P1 is:",p1)
the ordinary print() method will print the portion “P1 is:” and the remaining portion is taken care by
str ()__ method. In fact, str () method will return the string

1 March 2025 36
import math
class Point:
def __init__(self,a,b):
self.x=a
self.y=b
p1 x=10 x=4 p2
def dist(self,p2): y=20 y=5
d=math.sqrt((self.x-p2.x)**2 + (self.y-p2.y)**2)
return d

def __str__(self): Output:


return "(%d,%d)"%(self.x, self.y) P1 is: (10,20)
P2 is: (4,5)
p1= Point(10,20) The distance is: 16.15549442140351
p2=Point(4,5) # init () is called automatically

print("P1 is:",p1) # str () is called automatically


print("P2 is:",p2) # str () is called automatically

d=p1.dist(p2) #explicit call for dist()

print("The distance is:",d)


1 March 2025 37
Operator overloading
Ability of an existing operator to work on user-defined data type (class) is
known as operator overloading. It is a polymorphic nature of any object
oriented programming. Basic operators like +, -, * etc. can be overloaded.

• To overload an operator, one needs to write a method within user-


defined class.
• Python provides a special set of methods which have to be used for
overloading required operator
• The method should consist of the code what the programmer is willing
to do with the operator

1 March 2025 38
Object Object
one two Print( 5 +6 )
11

Print(‘sudar’ +’sanan’)
P=P1 + P2
sudarsanan
Def __add__()
-------
-------
-------

1 March 2025 39
special set of methods which have to be used for overloading required
operator

1 March 2025 40
Let us consider an example of Point class considered earlier Using operator
overloading, we can try to add two point objects
class Point:
def __init__(self,a=0,b=0): p1=Point(10,20)
self.x=a p2=Point(4,5)
X=10
self.y=b p1 Y=20
print( P1 is: ,p1)
def __add__(self,p2): print( P2 is: ,p2)
p3=Point()
p3.x=self.x + p2.x p4=p1+p2 #call for add () method X=4
p2
p3.y=self.y + p2.y print( Sum is: ,p4) Y=5
return p3 output

def __str__(self):
P1 is: (10,20)
return "(%d,%d)"%(self.x, self.y)
P2 is: (4,5)
Sum is: (14,25)

1 March 2025 41
Example 2
class A:
def __init__(self, a):
self.a = a

# adding two objects


def __add__(self, o): output
return self.a + o.a
3
ob1 = A(1) sudarsanan
ob2 = A(2)
ob3 = A("sudar")
ob4 = A("sanan")

print(ob1 + ob2)
print(ob3 + ob4)

1 March 2025 42
class A:

example3
def __init__(self, a):
self.a = a
class A:
def __lt__(self, other):
def __init__(self, a):
if(self.a<other.a):
self.a = a
return "ob1 is lessthan ob2"
def __gt__(self, other):
else:
if(self.a>other.a):
return "ob2 is less than ob1“
return True
else:
def __eq__(self, other):
return False
if(self.a == other.a): ob1 is lessthan ob2
return "Both are equal" Not equal
ob1 = A(2)
else:
ob2 = A(3)
return "Not equal“
if(ob1>ob2):
ob1 = A(2)
print("ob1 is greater than ob2")
ob2 = A(3)
else:
print(ob1 < ob2)
print("ob2 is greater than ob1")
output ob3 = A(4)
ob2 is greater than ob1 ob4 = A(4)
print(ob1 == ob2)
1 March 2025 43
Type-based dispatch
· When we try to perform addition, there are 3 cases –
o Adding two time objects like T3=T1+T2.
o Adding integer to Time object like T4=T1+75
o Adding Time object to an integer like T5=130+T1
Each of these cases requires different logic. When first two cases are considered, the
first argument will be T1 and hence self will be created and passed to
add () method. Inside this method, we will check the type of second argument
using isinstance() method. If the second argument is Time object, then we call
addTime() method. In this method, we will first convert both Time objects to integer
(seconds) and then the resulting sum into Time object again. So, we make use
time_to_int() and int_to_time() here. When the 2nd argument is an integer,
it is obvious that it is number of seconds. Hence, we need to call increment()
method.
Thus, based on the type of argument received in a method, we take appropriate
action. This
1 March 2025 is known as type-based dispatch. 44
# 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)
1 March 2025 45
In the 3rd case like T5=130+T1, Python tries to convert first argument
130 into self, which is not possible. Hence, there will be an error. This
indicates that for Python, T1+5 is not same as 5+T1 (Commutative law
doesn’t hold good!!). To avoid the possible error, we need to implement
right-side addition method radd ().

1 March 2025 46
A more
class Time:
complicated example
def __eq__(self,t):
return self.hour==t.hour and self.min==t.min and
def __init__(self, h=0,m=0,s=0): self.sec==t.sec
self.hour=h
self.min=m def __add__(self,t):
self.sec=s if isinstance(t, Time):
return self.addTime(t)
def time_to_int(self): else:
minute=self.hour*60+self.min return self.increment(t)
seconds=minute*60+self.sec
return seconds def addTime(self, t):
seconds=self.time_to_int()+t.time_to_int()
def int_to_time(self, seconds): return self.int_to_time(seconds)
t=Time()
minutes, t.sec=divmod(seconds,60) def increment(self, seconds):
t.hour, t.min=divmod(minutes,60) seconds += self.time_to_int()
return t return self.int_to_time(seconds)
def __radd__(self,t):
def __str__(self): return self.__add__(t)
return "%.2d:%.2d:%.2d"%(self.hour,self.min,self.sec)
1 March 2025 47
T1=Time(3,40)
T2=Time(5,45)
print("T1 is:",T1) output
print("T2 is:",T2)

print("Whether T1 is same as T2?", T1==T2) #call for eq () T1 is: 03:40:00


T2 is: 05:45:00
T3=T1+T2 #call for add () Whether T1 is same as T2? False
print("T1+T2 is:",T3) T1+T2 is: 09:25:00
T1+75= 03:41:15
T4=T1+75 #call for add () 130+T1= 03:42:10
print("T1+75=",T4) Using sum([T1,T2,T3,T4]): 22:31:15

T5=130+T1 #call for radd ()


print("130+T1=",T5)

T6=sum([T1,T2,T3,T4])
print("Using sum([T1,T2,T3,T4]):",T6)

1 March 2025 48
Working of above program is explained hereunder –

· The class Time has init () method for initialization of instance attributes
hour, min and sec. The default values of all these are being zero.
· The method time_to_int() is used convert a Time object (hours, min and sec)
into single integer representing time in number of seconds.
· The method int_to_time() is written to convert the argument seconds into time object in the
form of hours, min and sec. The built-in method divmod() gives the quotient as well as remainder after
dividing first argument by second argument given to it.
· Special method eq () is for overloading equality (==) operator. We can say one Time object is
equal to the other Time object if underlying hours, minutes and seconds are equal respectively. Thus, we
are comparing these instance attributes individually and returning either True of False.

1 March 2025 49
The beauty of Python lies in surprising the programmer with more facilities!! As we have
implemented add () method (that is, overloading of + operator), the built-
in sum() will is capable of adding multiple objects given in a sequence. This is due to
Polymorphism in Python. Consider a list containing Time objects, and then call sum()
on that list as –

T6=sum([T1,T2,T3,T4])

The sum() internally calls add () method multiple times and hence gives
the appropriate result. Note down the square-brackets used to combine Time
objects as a list and then passing it to sum().

1 March 2025 50
Polymorphism
What is Polymorphism : The word polymorphism means having many
forms. In programming, polymorphism means same function name (but
different signatures) being uses for different types.

Python program to demonstrate in-built poly- output


# morphic functions
5
3
# len() being used for a string
print(len("geeks"))

# len() being used for a list


print(len([10, 20, 30]))

1 March 2025 51
Example 2:
# A simple Python function to demonstrate
# Polymorphism

output
def add(x, y, z = 0):
return x + y+z 5
9
# Driver code
print(add(2, 3))
print(add(2, 3, 4))

1 March 2025 52
Interface and implementation
• One of the goals of object-oriented design is to make software more
maintainable, which means that you can keep the program working when
other parts of the system change, and modify the program to meet new
requirements.

• A design principle that helps achieve that goal is to keep interfaces


separate from implementations

•The package zope interface provides an implementation of “object


interfaces” for Python. It is maintained by the Zope Toolkit project.

1 March 2025 53
Def time_to_int()
class MyInterface(zope.interface.Interface): ----------
---------- Class X
-------------

def time_to Int()

def int_to_time()

def add_time()
Def time_to_int()
def increment() ---------- Class Y
----------
-------------

1 March 2025 54
example
import zope.interface

class MyInterface(zope.interface.Interface): class Myclass1:


def method1(self, x):
def method1(self, x): return x**3 output of obj1 is
pass def method2(self): 4
return "sudarsanan" foo
def method2(self):
output of obj2 is
pass 8
print( output of obj1 is )
sudarsanan
@zope.interface.implementer(MyInterface) obj=MyClass()
class MyClass: print(obj.method1(2))
def method1(self, x): print(obj.method2())
return x**2
def method2(self): print( output of obj2 is )
return "foo" obj1=Myclass1()
print(obj1.method1(2))
print(obj1.method2
1 March 2025 55
Module-5 end

1 March 2025 56

You might also like