0% found this document useful (0 votes)
42 views29 pages

Python Module - 4 - OOPs Notes (21EC643)

Uploaded by

Saha na
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
42 views29 pages

Python Module - 4 - OOPs Notes (21EC643)

Uploaded by

Saha na
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

PYTHON PROGRAMMING (21EC643)

Module-4

OBJECT ORIENTED PROGRAMMING IN PYTHON

CLASSES AND OBJECTS


Programmer defined type (Class)
Attributes (variables)
Rectangles
Copying
Debugging

CLASSES AND FUNCTIONS


Time
Pure Functions
Modifiers
Prototyping vs Planning,
Debugging

CLASSES AND METHODS


Object Oriented Features,
The init Method and str Method,
Operator Overloading,
Type-based dispatch,
Polymorphism,
Interface and Implementation,
Debugging

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

Introduction
• There are two main types of programming: procedural(structured) and Object-oriented.
• Procedural programming is about writing procedures or functions that perform operations
on the data, while object-oriented programming is about creating objects that contain both
data and functions. Object-oriented programming uses user defined types to organize both
code and data.
• Python is an object-oriented programming language, and class is a basis for any object-
oriented programming language.

Classes & Objects


• Class is a programmer (user)-defined data type which binds data and functions together into
single entity.
• Class is just a prototype (or a logical entity/blue print) to create the objects. It will not
consume any memory.
• An object is an instance of a class and it has physical existence. One can create any number
of objects for a class.
• A class in Python can be created using a keyword class.
Syntax:
1. class ClassName: # Creation of class
2. def __init__(self, parameter1, parameter2):
3. self.parameter1 = parameter1
4. self.parameter2 = parameter2
5.
6. def method1(self, parameter1, parameter2): # Method 1 definition
7. # Body of the method
8.
9. def method2(self, parameter1, parameter2): # Method 2 definition
10. # Body of the method
11.
12. # Create an instance or object of the class
13. obj = ClassName(value1, value2)
14.
15. # Access the attributes
16. a1 = obj.parameter1
17. a2 = obj.parameter1
18.
19. # Access the methods
20. y1 = obj.method1
21. y2 = obj.method2

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

Explanation :
Line 1-4: Creating class
Create a class named ClassName.
The __init__ method is a constructor used to initialize the attributes of the object.
The 'self' parameter represents the instance of the class and is used to access its attributes and
methods.

Line 6-12: define methods


Define a method named method1 with the parameters parameter1 and parameter2.
Define a method named method2 with the parameters parameter1 and parameter2.

Line 14-16: Creating objects


Create an instance (object) of the ClassName class and provide values for parameter1 and
parameter2.
Store the value of parameter1 from the object in the variable a1 and parameter2 in the
variable a2.

Line 17-18: Calling methods


Call the method1 using the dot operator and the object, and store the result in the variable y1.
Call the method2 using the dot operator and the object, and store the result in the variable y2.

Example 1: Class & Methods (Here methods are defined inside the class)
class Solve:
def __init__(self, a,b):
self.a=a
self.b=b

def add(self):
y1 = self.a + self.b
return (y1)

def mul(self,c):
y2 = self.a *self.b* c
return y2

a=3;
b=5;
c=8
obj = Solve(a,b) # Creation of object

y = obj.add()
z = obj.mul(c)

print("Sum of 2 numbers is: {y}”)

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

print("Product of 3 numbers: {z} “)

Here add function is defined is within the class. So it is accessed using the dot operator
Note : The number of variables passed to the __init__ function and the number of variables passed
during object creation should match. In this example, a and b are passed during object creation to match
the parameters a and b defined in the __init__ function.

Explanation:
1. Class Initialization (constructor (__init__)):
o Constructor (__init__) takes two parameters (a and b) and initializes the object's
attributes self.a and self.b
o Whenever an object of the Solve class is created, the constructor initializes the object's
attributes with the provided values.
2. Methods:
o The add method does not take any parameters other than self. It adds the object's
attributes self.a and self.b and returns the result.
o The mul method takes an additional parameter (c) besides self. It multiplies the object's
attributes self.a and self.b with c and returns the result.
3. Object Creation:
o An object obj of the Solve class is created with the variables a and b.
4. Method Call:
o Methods are called on object using dot (.) operator.
o Add method is called on the obj object, and the result is stored in the variable y.
o The mul method is called on the obj object with the variable c, and the result is stored in
the variable z.
5. Output:
o The results are printed using formatted strings, displaying the sum of the two numbers and
the product of the three numbers.

Note:
• The number of variables passed to the __init__ function and the number of variables passed
during object creation should match. In this example, a and b are passed during object creation to
match the parameters a and b defined in the __init__ function.

Example 2: With out using init constructor


class Solve:
def add(self, a, b):
y1 = a + b
return y1

def mul(self, a, b):


y2 = a * b
return y2

a = 5
b = 10

obj = Solve() # Creation of object

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

y = obj.add(a, b)
z = obj.mul(a, b)

print("Sum of 2 numbers is:", y)


print("Product of 2 numbers:", z)

If init is not used, we have to the pass the variables to functions not, while creating the object.
Explanation: Write the explanation in your own words

Another Example
#To create the class (without init)
class student:
name="Virat"
sem=6
college="SGBIT"

#To create the object


obj1=student()

#To access the class members


print(obj1.name)
print(obj1.sem)

Here name, sem, college are defined within the class, so they are
accessed using dot operator

Example 3: Classes and Functions Methods defined outside the class


class Solve:
pass #cretaing empty class

def add(a, b): #defining function outside the class


y = a + b
return y

# Creating the objects


obj = Solve()

# Attributes & Assigning values to attributes


obj.a = 10.0
obj.b = 20.0

# Call the function through the object


z = add(obj.a, obj.b) #function is defined outside the class, so not using obj.add
print(z)

Here add function is defined is outside the class. So it is called directly with out using the dot
operator

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

Explain the class and object concepts


Class
• Class is a user-defined data type which binds data and functions together into single entity.
• Class is just a prototype (or a logical entity/blue print) to create the objects. It will not
consume any memory.
• A class is defined using the class keyword followed by the class name
Object
• An object is an instance of a class and it has physical existence (consumes memory). One
can create any number of objects for a single class.
Instantiation
• The process of Creating new instance or object is called instantiation.
• Objects are created by assigning class name to variable.
• All the methods are called on an object using dot operator.
Attributes:
o The variables associated with objects are called attributes

#Cetaing class
class Solve:
def __init__(self, a, b): #init constructor
self.a=a
self.b=b

def add(self):
y1 = self.a + self.b
return (y1)

def mul(self,c):
y2 = self.a *self.b* c
return y2

a=3;
b=5;
c=8

#creation of object
obj = Solve(a,b)

y = obj.add()
z = obj.mul(c)

print("Sum of 2 numbers is: {y}”)


print("Product of 3 numbers: {z} “)

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

Explanation:
Creation of Class
Class Solve is created using keyword class

init_ constructor or Class Initialization


• The __init__ method is a special method in classes known as the constructor.
• Whenever an object is created, the constructor is called automatically, and it initializes the
object's attributes with the provided values.
• Constructor (__init__) takes two parameters (a and b) and initializes the object's attributes
self.a and self.b

Defining the Methods:


o 2 methods have been defined here
o The add method does not take any parameters other than self. It adds the object's attributes
self.a and self.b and returns the result.
o The mul method takes an additional parameter (c) besides self. It multiplies the object's
attributes self.a and self.b with c and returns the result.

Object Creation( Instantiation)


o An object obj is created by assigning the class name Solve to the variable obj
o Here object is created with the variables a and b.
o obj = Solve(a,b)

Method Call:
o Methods are called on object using dot (.) operator.
o Add method is called on the obj object, and the result is stored in the variable y.
o The mul method is called on the obj object with the variable c, and the result is stored in the
variable z.

Output:
• The results are printed using formatted strings, displaying the sum of the two numbers and the
product of the three numbers.

Note:
• The number of variables passed to the __init__ function and the number of variables passed
during object creation should match. In this example, a and b are passed during object creation to
match the parameters a and b defined in the __init__ function.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

Explain Attributes
• Variables associated with either object or class are called attributes

Class Attributes: Variables of a Class


o These are variables defined within a class but outside of any methods.
o They are shared by all instances (objects) of the class.
o They are accessed using the class name, not through objects

Instance Attributes: Variables of an Object


• These are variables defined within methods or the __init__ method of a class.
• They are specific to each instance (object) of the class.
• They are accessed using the object (instance) name.

Example:

class Solve:
#class variables (inside the class)
class_var_a=50;
class_var_b=60;

def __init__ (self, a,b)


self.a=a # Instance(object) variable
self.b=b # Instance variable

def add(self):
y1 = self.a +self.b
return y1

#regular variables
a=2;
b=5;

#creating the object


obj = Solve( )

#object(instance) variables & assigning values to object attributes


obj.a=10
obj.b=20

z1= obj.add(a, b)
z2 = obj.add(obj.a, obj.b)
z3= obj.add(class_var_a, class_var_b)

print(f "z1={z1}, z2={z2}, z3={z3}”)

Output: z1=7, z2=30, z3= 110

Assigning values to attributes:


We can assign values to object attributes using dot operator

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

obj.a =10.0
obj.b =20.0

Object diagram
• A state diagram of object and its attributes is called as object diagram.
Solve
a 10.0
obj
b 20.0

Accessing the attribute :


We can access each attribute of object using dot operator
print(obj.a)
Output: 10.0

print(obj.b)
Output: 20.0

Attributes of an object can be assigned to other variables


a= obj.a
print(a)
Output: 10.0

• Here, the variable a is normal variable is nothing to do with attribute a.


• So, there is no any name conflict between normal program variable and attributes of an object.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

Write python program to find the area and perimeter of rectangle using oops
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: "))

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(f'The area of rectangle: {y}’)


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

Explain this program in your own words

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

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.

Program:
import math

class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y

def read_point(self):
self.x = float(input("Enter the x-coordinate: "))
self.y = float(input("Enter the y-coordinate: "))
return (self.x, self.y)

#function to print coordinates


def print_point(self):
print(f' coordinates are :{self.x}\t {self.y}')

#Create the 2 objects of Point class;


#here p1 has 2 variables (x,y) and p2 has 2 variables x and y)
p1=Point()
p2=Point()

#Pass the objects of Point to method to compute Euclidian distance


@staticmethod
def distance(p1, p2):
dx = p2.x - p1.x
dy = p2.y - p1.y
dist = math.sqrt(dx**2 + dy**2)
return dist

# Call the read function to obtain coordinates of p1 and p2


p1.Z1=p1.read_point()
p2.Z2=p2.read_point()

# Print the coordinates of p1 and p2


p1.print_point(p1.z1)
p2.print_point(p2.z2)

# Calculate the distance between p1 and p2 using the distance method


dist = Point.distance(p1.z1, p2.z2)
print(f"Distance between p1 and p2: {dist}")

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

Output:

Method 2: defining function outside the class


import math

class Point:
pass

# Defining the methods outside the class


def read_point(p):
p.x = float(input("Enter the x coordinate:"))
p.y = float(input("Enter the y coordinate:"))
return p.x, p.y

def print_point(p):
print(" {p.x}, {p.y}”)

#passing the objects (p1, p2) to function distance


def distance(p1, p2):
d = math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)
return d

#Create 2 objects
p1=Point()
p2=Point()

# Calling the functions (since these are outside class, no need to call
using objects, directly pass the object.
Z1=read_point(p1)
Z2=read_point(p2)

dist = distance(p1, p2)

# To print the values


print_point(z1)
print_point(z2)

print("Distance is: {dist}”)

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

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 find_center() to compute centre point of the rectangle
▪ A function resize() to modify the size of rectangle
▪ A function to print corner point as an ordered-pair

class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y

def print_point(self):
print(f"({self.x}, {self.y})")

corner_point= Point (1,1)

class Rectangle:
def __init__(self, width, height, corner_point):
self.width = width
self.height = height
self.corner = corner_point #corner is object of point class

def find_center(self):
center_x = self.corner.x + self.width / 2
center_y = self.corner.y + self.height / 2
return Point (center_x, center_y)

def resize(self, w, h):


self.width = self.width +w
self.height = self.height + h
return self.width, self.height

def print_corner(self):
self.corner.print_point()

# Creating object of Rectangle class


rect = Rectangle(100, 200, corner_point)

print(f"Original Rectangle: width={rect.width}, height={rect.height}")

center = rect.find_center()
print(f"The center of the rectangle is: {center.x}, {center.y}”)

resized = rect.resize(50, 70)


print(f" Rectangle after resize: width={resized[0]}, height={resized[1]}")

print("The corner point of the rectangle is: ")


rect.print_corner()

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

Another way : Program:


(In this program, object of point is directly created inside the rectangle class, easy to understand)
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y

def print_point(self):
print(f"({self.x}, {self.y})")

class Rectangle:
def __init__(self, width, height, corner_x, corner_y):
self.width = width
self.height = height
self.corner = Point(corner_x, corner_y) # corner is an object of Point class

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 resize(self, w, h):


self.width += w
self.height += h
return self.width, self.height

def print_corner(self):
self.corner.print_point()

# Creating object of Rectangle class


rect = Rectangle(100, 200, 1, 1)

print(f"Original Rectangle: width={rect.width}, height={rect.height}")

center = rect.find_center()
print(f"The center of the rectangle is: {center.x}, {center.y}")

resized = rect.resize(50, 70)


print(f"Rectangle after resize: width={resized[0]}, height={resized[1]}")

print("The corner point of the rectangle is: ")


rect.print_corner()

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

Another way : Methods defined outside the Class


class Rectangle:
''' Blank class'''

class Point:
''' Blank class'''

#method to modify the size of rectangle


def resize(rect,w, h):
rect.width= rect.width+w
rect.height=rect.height+h

#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

# Creating object of rectangle class


box=Rectangle() #create Rectangle object
box.width=100 #assign value to width
box.height=200 # assign value to height

#Creating object of Point class


p=Point() #create Point object
box.corner=Point() # Creating point object which is attribute of box
box.corner.x=0 #corner has two attributes x and y
box.corner.y=0 #initialize x and y to 0

#method to print center


def print_point(p):
print("(%g,%g)"%(p.x, p.y))

print("Original Rectangle is:")


print("width=%g, height=%g"%(box.width, box.height))

center=find_center(box) #call the center function


print("The center of rectangle is:")
print_point(center) #call the print centre function

resize(box,50,70)
print("Rectangle after resize:")
print("width=%g, height=%g"%(box.width, box.height))

center=find_center(box)
print("The center of resized rectangle is:")
print_point(center)

Working of above program:

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

Explain Instances as Return Values


• Functions can values or return instances (objects).
• Example: find_center() function returns the object of Point class
method to find the centre of rectangle (object of rectangle is passed)
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

Here, this function takes an object self (object of rectangle) as an argument. And this function
returns the object of class point.

• Input:
• It takes the self parameter, which refers to the current instance of the Rectangle class.
This means it operates on the specific rectangle object that calls this method.

• Calculations & Creation of Point Instance:


• The find_center() method calculates the center coordinates (center_x and center_y) using
the attributes of self.corner, which is an instance of the Point class
• Then it returns a object of Point class representing the center of the rectangle.

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

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

Explain Aliasing & Copying


Aliasing
• Aliasing means: multiple variables referencing the same object in memory (Referring same
object with different names)
• Aliasing happens when one object is assigned to another object of the same class.
• This may happen in following situations
o Direct object assignment (like p2=p1)
o When an object is passed as an argument to a function
o When an object is returned from a function

Direct object assignment (like p2=p1)


list1 = [1, 2, 3]
list2 = list1 # list2 now aliases list1

o Both list1 and list2 point to the same list [1, 2, 3] in memory. They are aliases of each other.
o Effect: Changes made in one alias, affects other object. Because both have same memory
Example:
list2.append(4)
print(list1)
print(list2)
# Output: list1= [1, 2, 3, 4]
list2=[1, 2, 3, 4]

______________________________________________________________________
Copying
o Copying creates a new object with the same value as the original, independent of the original
object. Here both copied and original will have different memory locations
o To copy, we have to use inbuilt method .copy() from library copy
o There are 2 types of Copy
1. Shallow copy
2. Deep copy

Shallow copy:
The operation in which copying the contents of objects as well as copying the references to
embedded object is called shallow copy. This type of copy operation is performed using copy
function in copy module ( copy.copy())
Example 1
import copy

list1 = [1, 2, 3, [8, 9]]


list2 = copy.copy(list1) # Shallow copy using copy() method

list2.append(50) # Modify the list2

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

print("Original list1:", list1) # Output: [1, 2, 3, [8, 9,]]


print("Modified list2:", list2) # Output: [1, 2, 3, [8, 9], 50]

Example 2
import copy

list1 = [1, 2, 3, [8, 9]]


list2 = copy.copy(list1) # Shallow copy using copy() method

list2[3].append(50) # Modify the nested list in list2


print("Original list1:", list1) # Output: [1, 2, 3, [8, 9, 50]]
print("Modified list2:", list2) # Output: [1, 2, 3, [8, 9, 50]]

Explanation:
• Only the top-level elements (like integers or strings) of object are duplicated. It does not
duplicate nested objects; but it only copies references of nested objects, but the NOT actual
elements of nested object.
• Impact: Changes made to the nested objects in the shallow copy can affect the original
object.
• In example 1: the value 50 is appeneded to list2, but does not affect the list1 (ie it is not
appended to list1)
• In example 2: It is case of nested object. When we appended the 50 in the nested object of
list2, even list1 got affected and value 50 also got added to list1

2. Deep copy
o The operation in which copying the contents of objects as well as copying the embedded
objects is called deep copy. This type of copy operation is performed using deepcopy
function in copy module (copy.deepcopy())

Example 1 appending to top level object


import copy

list1 = [1, 2, 3, [8, 9]]


list2 = copy.deepcopy(list1) # Shallow copy using copy() method

list2.append(50) # Modify the list2


print("Original list1:", list1) # Output: [1, 2, 3, [8, 9,]]
print("Modified list2:", list2) # Output: [1, 2, 3, [8, 9], 50]

Example 2 : appending to nested object


import copy

list1 = [1, 2, 3, [8, 9]]

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

list2 = copy.deepcopy(list1) # Shallow copy using copy() method

list2[3].append(50) # Modify the nested list in list2


print("Original list1:", list1) # Output: [1, 2, 3, [8, 9]]
print("Modified list2:", list2) # Output: [1, 2, 3, [8, 9], 50]

Explanation:
• Here all elements of object, including nested object are duplicated. The copy and original
objects are fully independent to each other
• Impact: Changes made to the nested objects in the deep copy can NOT affect the original
object.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

Classes and Function


We can write the user defined functions which takes objects as parameters and return the object

Time ( define a class called Time that records the time of day)
Example: To write python program to 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(self):
print(f'{self.hour:02}:{self.minute:02}:{self.second:02}')

t = Time(11, 59, 30)


t.display()

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

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

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

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

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.

Prototyping v/s Planning


Prototype and Patch
• Whenever we do not have the deep understanding of the complete problem statement, then
first we have to write the rough prototype or program with available information for basic
calculation, test and patch (correct) the errors. Then modify the program incrementally as and
when more information is available and patch (correct) the errors. This methodology is known
as prototype and patch.
• Drawback: But, this type of incremental development may end-up in unnecessary code, with
many special cases and it may become unreliable
Designed development
• A development plan that involves high-level insight into the problem and more planning than
incremental development or prototype development. This makes the programming much
easier.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

• For example, if we consider the problem of adding two-time objects. This problem involves
the numbers with base 60 (as every hour is 60 minutes and every minute is 60 seconds), proper
planning before coding makes the things easier.

Classes and Methods


• Python is object-oriented programming, that means it supports object-oriented characteristics.
• The OOPS Features or Characteristics:
o Programs include class and method definitions.
o Most of the computation is expressed in terms of operations on objects.
o Objects often represent things in the real world, and methods often correspond
• To establish relationship between the object of the class and a function, we must define a
function as a member of the class.

Difference between Method and function


• 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

Program to explain the method and function


# Function defined outside the class
def function_area(height, width):
return height * width

# Class definition
class Rectangle:
def __init__(self, height, width):
self.height = height
self.width = width

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

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

# Input from user


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

# Creating an object of Rectangle class


obj = Rectangle(a, b)

# Calling function/methods to calculate area and perimeter


y = function_area(obj.height, obj.width) # Using the function directly
z = obj.perimeter() # Method call using object

# Displaying results
print('The area of rectangle using function:', y)
print('The Perimeter of rectangle using method:', z)

The init Method


• __init__() is special method which is called automatically when the object created. This
method is used to initialize the object attributes
• The double underscores at both sides of the __init__() method indicate that Python will use
the method internally.
• The word 'self' is used to represent the object of a class. By using the "self" keyword we can
access the attributes and methods of the class.

Example:

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

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

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


• __str__(). is a special method used for string representation of user defined python objects
• Usually, print() is used to print the basic types in Python. But, user-defined types (class
objects) have their own meaning and a way of representation.
• For string representation of the user defined types, we can use str method

#implementation of __str__ method


class Student():
def __init__(self,name, roll_no):
self.name = name
self.roll_no= roll_no

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

Operator Overloading
• Operator overloading refers to the ability of a built-in operator to behave differently
according to the different operands.
• It is a case of polymorphism, where operators have different implementations based on
operands or parameters
• For example, the operator ‘+’ is used to:
o Add two integers.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

o Concatenate two strings.


o Merge two lists.

Operator overloading: To perform the operator overloading, python provides some special
function or magic function which automatically gets invoked, when associated with that particular
operator. The method should begin and end with a double underscore (__).

For example, To overload the '+' operator, we will 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

# 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

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.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

Example1:
a = 23
b = 11
print(a+b) #addition of 2 integers
Output: 23

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)

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

Another Example:
User defined function: Histogram
Histogram function to count the number of times each letter appears in a word
s='dhonii'
def histogram(s):
d = dict()
for i in s:
if i not in d:
d[i] = 1
else:
d[i] += 1
return d

histogram(s) #function call

Output: {'d': 1, 'h': 1, 'i': 2, 'n': 1, 'o': 1}

• This function also works for lists, tuples, and even dictionaries.
• Functions which work with several types are called polymorphic.

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
class Child_Solve(Parent_Solve):
def multiply(self):
z = self.a * self.b
return z

# Creating an object of the child class

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING (21EC643)

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)

Prof. Sujay Gejji ECE, SGBIT, Belagavi

You might also like