PYTHON PROGRAMMING - 1BPLC205B
MODULE 5
[Link] ORIENTED PROGRAMMING:
1.1 OBJECTS ARE MUTABLE:
Definition
An object is mutable if its data can be changed after it is created.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "({0}, {1})".format(self.x, self.y)
class Rectangle:
def __init__(self, posn, w, h):
[Link] = posn
[Link] = w
[Link] = h
def __str__(self):
return "({0}, {1}, {2})".format([Link],
[Link],
[Link])
def grow(self, delta_width, delta_height):
[Link] += delta_width
[Link] += delta_height
def move(self, dx, dy):
[Link].x += dx
[Link].y += dy
# Main Program
r = Rectangle(Point(10, 5), 100, 50)
print("Original Rectangle:")
print(r)
[Link](25, -10)
print("\nAfter grow(25, -10):")
print(r)
PROF. VIBHA RAMESH NAIK| GEC,KARWAR
PYTHON PROGRAMMING - 1BPLC205B
[Link](-10, 10)
print("\nAfter move(-10, 10):")
print(r)
grow() Method
def grow(self, delta_width, delta_height):
[Link] += delta_width
[Link] += delta_height
• Used to increase or decrease the size of a rectangle.
• Changes the width and height values.
Example:
[Link](25, -10)
New width = 125
New height = 40
move() Method
def move(self, dx, dy):
[Link].x += dx
[Link].y += dy
• Used to move the rectangle to a new position.
• Changes the x and y coordinates of the corner.
Example:
[Link](-10, 10)
Corner changes from (10, 5) to (0, 15).
Output
Before changes:
((10, 5), 100, 50)
After grow(25, -10):
((10, 5), 125, 40)
After move(-10, 10):
((0, 15), 125, 40)
PROF. VIBHA RAMESH NAIK| GEC,KARWAR
PYTHON PROGRAMMING - 1BPLC205B
Key Point
Rectangle objects are mutable because their attributes (width, height, and position) can
be modified after the object is created.
1.2 SAMENESS
Sameness refers to comparing two objects to determine whether they are identical.
There are two types of sameness:
1. Shallow Equality
• Checks whether two variables refer to the same object in memory.
• Uses the is operator.
Example:
p1 = Point(3, 4)
p2 = Point(3, 4)
print(p1 is p2)
Output:
False
Although p1 and p2 have the same coordinates, they are different objects.
If:
p3 = p1
print(p1 is p3)
Output:
True
Because both variables refer to the same object.
2. Deep Equality
• Checks whether two objects contain the same data.
• Compares the values stored in the objects.
Example:
def same_coordinates(p1, p2):
return (p1.x == p2.x) and (p1.y == p2.y)
PROF. VIBHA RAMESH NAIK| GEC,KARWAR
PYTHON PROGRAMMING - 1BPLC205B
p1 = Point(3, 4)
p2 = Point(3, 4)
print(same_coordinates(p1, p2))
Output:
True
Because both points have the same coordinates.
1.3 COPYING
Copying is used to create a duplicate of an object. It helps avoid problems caused by aliasing,
where multiple variables refer to the same object.
Python provides the copy module for copying objects.
Shallow Copy
A shallow copy creates a new object but does not copy the embedded objects. Instead, it
copies their references.
Example:
import copy
p1 = Point(3, 4)
p2 = [Link](p1)
p1 is p2 # False
p1 and p2 are different objects, but they contain the same data.
Shallow copying works well for simple objects like Point.
Problem with Shallow Copy
For complex objects such as Rectangle, which contains a Point object, shallow copy copies
only the reference to the embedded object.
b2 = [Link](b1)
Both rectangles share the same corner point. Therefore, changing the corner of one rectangle
affects the other rectangle as well.
This can lead to confusing and error-prone behavior.
Deep Copy
A deep copy creates a new object and also copies all embedded objects.
PROF. VIBHA RAMESH NAIK| GEC,KARWAR
PYTHON PROGRAMMING - 1BPLC205B
Example:
import copy
b2 = [Link](b1)
Now b1 and b2 are completely independent. Changes made to one object do not affect the
other.
2. INHERITANCE
2.1 PURE FUNCTIONS:
A pure function is a function that does not change the original objects. It creates a new object
and returns it as the result.
The add_time() function is a pure function because it adds two MyTime objects and returns a
new MyTime object without modifying the original objects.
Program
class MyTime:
def __init__(self, h, m, s):
[Link] = h
[Link] = m
[Link] = s
def __str__(self):
return str([Link]) + ":" + str([Link]) + ":" + str([Link])
def add_time(t1, t2):
h = [Link] + [Link]
m = [Link] + [Link]
s = [Link] + [Link]
if s >= 60:
s = s - 60
m=m+1
if m >= 60:
m = m - 60
h=h+1
return MyTime(h, m, s)
PROF. VIBHA RAMESH NAIK| GEC,KARWAR
PYTHON PROGRAMMING - 1BPLC205B
current_time = MyTime(9, 14, 30)
bread_time = MyTime(3, 35, 0)
done_time = add_time(current_time, bread_time)
print(done_time)
Output
12:49:30
Important Points
• A pure function does not modify existing objects.
• It creates and returns a new object.
• add_time() is a pure function because it returns a new MyTime object without changing
the original time objects.
2.2 MODIFIERS:
A modifier is a function that changes the object passed to it as a parameter.
Unlike a pure function, a modifier modifies the original object instead of creating a new
object.
The increment() function is a modifier because it adds a given number of seconds directly to a
MyTime object.
Program
class MyTime:
def __init__(self, h, m, s):
[Link] = h
[Link] = m
[Link] = s
def __str__(self):
return str([Link]) + ":" + str([Link]) + ":" + str([Link])
def increment(t, seconds):
[Link] += seconds
PROF. VIBHA RAMESH NAIK| GEC,KARWAR
PYTHON PROGRAMMING - 1BPLC205B
while [Link] >= 60:
[Link] -= 60
[Link] += 1
while [Link] >= 60:
[Link] -= 60
[Link] += 1
t = MyTime(9, 14, 30)
print("Before increment:", t)
increment(t, 100)
print("After increment :", t)
Output
Before increment: 9:14:30
After increment : 9:16:10
Key Note
• A modifier is a function that changes the state of an object.
• It modifies the original object passed as an argument.
• The increment() function is a modifier because it directly updates the hours, minutes,
and seconds of the MyTime object.
Difference:
• Pure Function → Creates a new object.
• Modifier → Changes the existing object.
2.3 GENERALIZATION:
Generalization means solving a problem in a more general and simpler way instead of
handling many special cases.
In the MyTime class, it is easier to convert time into total seconds, perform calculations, and
then convert it back to hours, minutes, and seconds.
PROF. VIBHA RAMESH NAIK| GEC,KARWAR
PYTHON PROGRAMMING - 1BPLC205B
Advantages
• Makes the program shorter.
• Easier to understand.
• Easier to debug.
• Reduces errors.
• New features can be added easily.
Example
Instead of adding hours, minutes, and seconds separately, convert both times to seconds, add
them, and convert the result back to time.
2.4 OPERATOR OVERLOADING:
Operator Overloading is a feature in Python that allows operators such as +, -, and * to have
different meanings for different types of objects.
Python allows programmers to redefine the behavior of operators for user-defined classes
using special methods such as __add__(), __sub__(), __mul__(), and __rmul__().
Example 1: Overloading + Operator in MyTime Class
def __add__(self, other):
return MyTime(0, 0,
self.to_seconds() + other.to_seconds())
Usage:
t1 = MyTime(1, 15, 42)
t2 = MyTime(3, 50, 30)
t3 = t1 + t2
Output:
05:06:12
Here, the + operator adds two MyTime objects.
Example 2: Overloading + Operator in Point Class
def __add__(self, other):
return Point(self.x + other.x,
self.y + other.y)
This adds the corresponding coordinates of two points.
Example 3: Overloading * Operator
PROF. VIBHA RAMESH NAIK| GEC,KARWAR
PYTHON PROGRAMMING - 1BPLC205B
def __mul__(self, other):
return self.x * other.x + self.y * other.y
This computes the dot product of two points.
p1 = Point(3, 4)
p2 = Point(5, 7)
print(p1 * p2)
Output:
43
Example 4: Scalar Multiplication
def __rmul__(self, other):
return Point(other * self.x,
other * self.y)
Usage:
print(2 * p2)
Output:
(10, 14)
2.5 POLYMORPHISM:
Polymorphism means "many forms". It allows the same function or operator to work with
different types of objects.
A function that can accept arguments of different types is called a polymorphic function.
Example:
def multadd(x, y, z):
return x * y + z
This function works with:
• Numbers
multadd(3, 2, 1)
Output:
PROF. VIBHA RAMESH NAIK| GEC,KARWAR
PYTHON PROGRAMMING - 1BPLC205B
• Point objects
multadd(2, p1, p2)
Output:
(11, 15)
Python follows the Duck Typing Rule:
If an object supports all the operations required by a function, then the function can be used
with that object.
Advantages
• Code reusability.
• Flexibility.
• Same function works for different data types.
• Reduces code duplication.
3. EXCEPTIONS
3.1 CATCHING EXCEPTIONS:
Definition
An exception is a runtime error that occurs during program execution. When an exception
occurs, the program normally stops and displays an error message.
Examples of exceptions:
• ZeroDivisionError – dividing a number by zero.
• IndexError – accessing an invalid list index.
• TypeError – performing an invalid operation on a data type.
• FileNotFoundError – opening a file that does not exist.
Catching Exceptions
Python provides the try-except statement to handle exceptions and prevent the program from
crashing.
Syntax
PROF. VIBHA RAMESH NAIK| GEC,KARWAR
PYTHON PROGRAMMING - 1BPLC205B
try:
# Code that may cause an exception
except ExceptionType:
# Code to handle the exception
Example
filename = input("Enter file name: ")
try:
f = open(filename, "r")
except FileNotFoundError:
print("File not found")
If the file does not exist, the program displays an error message instead of stopping.
Components of try Statement
1. try Block:
Contains code that may generate an exception.
2. except Block:
Handles the exception if it occurs.
3. else Block:
Executes when no exception occurs.
4. finally Block:
Executes whether an exception occurs or not.
Example
user_input = input("Enter a number: ")
try:
n = float(user_input)
except ValueError:
print("Invalid input")
else:
print("Square =", n*n)
PROF. VIBHA RAMESH NAIK| GEC,KARWAR
PYTHON PROGRAMMING - 1BPLC205B
finally:
print("Thank You")
Handling Multiple Exceptions
A single try block can handle multiple exceptions.
try:
f = open("[Link]")
except FileNotFoundError:
print("File not found")
except PermissionError:
print("Permission denied")
Advantages of Exception Handling
1. Prevents abnormal program termination.
2. Improves program reliability.
3. Allows graceful handling of errors.
4. Makes debugging easier.
5. Improves user experience.
3.2 RAISING OUR OWN EXCEPTIONS
Definition
Python allows programmers to raise their own exceptions when an error condition is detected
in a program.
The raise statement is used to create and generate an exception explicitly.
Syntax
raise ExceptionType("Error Message")
Example Program
PROF. VIBHA RAMESH NAIK| GEC,KARWAR
PYTHON PROGRAMMING - 1BPLC205B
def get_age():
age = int(input("Enter your age: "))
if age < 0:
raise ValueError(str(age) + " is not a valid age")
return age
print(get_age())
Output 1
Enter your age: 25
25
Output 2
Enter your age: -2
ValueError: -2 is not a valid age
Working
1. User enters age.
2. Program checks whether age is negative.
3. If age is less than 0, a ValueError exception is raised.
4. The exception travels through function calls until it is handled by a try-except block.
5. If not handled, Python displays an error message and stops execution.
Advantages
• Helps detect invalid data.
• Improves program reliability.
• Allows custom error checking.
• Makes debugging easier.
PROF. VIBHA RAMESH NAIK| GEC,KARWAR
PYTHON PROGRAMMING - 1BPLC205B
PROF. VIBHA RAMESH NAIK| GEC,KARWAR