0% found this document useful (0 votes)
1 views25 pages

Python Module 5 Notes

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views25 pages

Python Module 5 Notes

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Prerana Educational and Social Trust®

PES Institute of Technology and


Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

Module 5:
o Object Oriented Programming

Objects are Mutable


Sameness (Object Identity and Equality)
Copying Objects
Shallow Copy
Deep Copy

o Inheritance and Advanced OOP Concepts

Pure Functions
Modifiers
Generalization
Operator Overloading
Polymorphism

o Exception Handling

Catching Exceptions
Raising User-Defined Exceptions

Object Oriented Programming Concepts

 Objects are Mutable


 Sameness
 Copying

Objects are Mutable

 An object is mutable if its state (data) can be changed after creation.


 In Python, lists, dictionaries, and class objects are mutable.
 Changes made to a mutable object affect the same object in memory.
 Mutability helps in efficient memory usage.

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 1


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

class Student:
def __init__(self, name, marks):
[Link] = name
[Link] = marks

s1 = Student("Anu", 80)

print("Before change:", [Link])

[Link] = 90 # modifying object

print("After change:", [Link])

Output

Before change: 80
After change: 90

Sameness

 Sameness means two references point to the same object in memory.


 If two variables refer to the same object, changes through one reference
will be reflected in the other.
 Checked using the is operator.
 Sameness is also called aliasing.

class Book:
def __init__(self, pages):
[Link] = pages

b1 = Book(100)
b2 = b1 # both refer to same object

[Link] = 150

print("Pages in b1:", [Link])

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 2


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

print("Pages in b2:", [Link])


print("Same object:", b1 is b2)

Output

Pages in b1: 150


Pages in b2: 150
Same object: True

Copying

 Copying creates a new object with the same data.


 Changes made to the copied object do not affect the original.
 Two types:
o Shallow Copy – copies reference
o Deep Copy – copies complete object
 Copying avoids unintended changes.

a) Shallow Copy

 Only the reference is copied.


 Changes in one object affect the other.

Program
class Student:
def __init__(self, marks):
[Link] = marks

s1 = Student(85)
s2 = s1 # shallow copy

[Link] = 95

print("Marks of s1:", [Link])


print("Marks of s2:", [Link])

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 3


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

Output
Marks of s1: 95
Marks of s2: 95

b) Deep Copy

 A new object is created with copied values.


 Changes do not affect the original object.

Program
class Student:
def __init__(self, marks):
[Link] = marks

s1 = Student(85)

# Creating a deep copy manually


s2 = Student([Link])

[Link] = 95

print("Marks of s1:", [Link])


print("Marks of s2:", [Link])

Output
Marks of s1: 85
Marks of s2: 95

Note:
Mutable : Object data can be changed
Sameness : Two names refer to same object
Copying : New object is created

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 4


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

Inheritance and Advanced OOP Concepts

Pure Functions
Modifiers
Generalization
Operator Overloading
Polymorphism

Inheritance in Python:

Inheritance is an Object-Oriented Programming (OOP) feature where one class (child class)
can use the properties and methods of another class (parent class).

Advantages:

 Reusing code
 Reducing duplication
 Making programs cleaner

Syntax

class Parent:
# parent attributes and methods

class Child(Parent):
# child attributes and methods

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 5


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

The child class automatically gets access to the parent class methods.

Inheritance Example

# Parent Class
class A:
def displayA(self):
print("This is Class A (Parent Class)")

# Child Class
class B(A): # B inherits A
def displayB(self):
print("This is Class B (Child Class)")
# Creating object of Child Class

obj = B()

# Calling methods
[Link]() # from Parent Class A
[Link]() # from Child Class B

Output

This is Class A (Parent Class)


This is Class B (Child Class)

Types of Inheritance

1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 6


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

Multilevel Inheritance Example

# Parent Class
class A:
def displayA(self):
print("This is Class A (Parent Class)")

# Child Class of A
class B(A):
def displayB(self):
print("This is Class B (Child Class of A)")

# Child Class of B (Grandchild of A)


class C(B):
def displayC(self):
print("This is Class C (Child of B)")

# Creating object of Class C


obj = C()

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 7


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

# Calling methods from all levels


[Link]() # from Class A
[Link]() # from Class B
[Link]() # from Class C

Output

This is Class A (Parent Class)


This is Class B (Child Class of A)
This is Class C (Child of B)

Multiple Inheritance Example

# Parent Class 1
class A:
def displayA(self):
print("This is Class A")

# Parent Class 2
class B:
def displayB(self):
print("This is Class B")

# Child Class inheriting from both A and B


class C(A, B):
def displayC(self):
print("This is Class C (Child of A and B)")

# Creating object of Class C


obj = C()

# Calling methods from both parents


[Link]()
[Link]()
[Link]()

Output

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 8


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

This is Class A
This is Class B
This is Class C (Child of A and B)

Hierarchical Inheritance Example

# Parent Class
class A:
def displayA(self):
print("This is Class A (Parent Class)")

# Child Class 1
class B(A):
def displayB(self):
print("This is Class B (Child of A)")

# Child Class 2
class C(A):
def displayC(self):
print("This is Class C (Child of A)")

# Creating objects of B and C


obj1 = B()
obj2 = C()

# Calling methods
[Link]()
[Link]()

[Link]()
[Link]()

Output

This is Class A (Parent Class)


This is Class B (Child of A)
This is Class A (Parent Class)
This is Class C (Child of A)

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 9


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

Hybrid Inheritance Example

This example combines Hierarchical + Multiple Inheritance.

A
/ \
B C
\ /
D
# Parent Class
class A:
def displayA(self):
print("This is Class A (Parent Class)")

# Child Class 1
class B(A):
def displayB(self):
print("This is Class B (Child of A)")

# Child Class 2
class C(A):
def displayC(self):
print("This is Class C (Child of A)")

# Class D inherits from both B and C (Multiple Inheritance)


class D(B, C):
def displayD(self):
print("This is Class D (Child of B and C)")

# Creating object of Class D


obj = D()

# Calling methods
[Link]() # From A
[Link]() # From B
[Link]() # From C
[Link]() # From D

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 10


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

Output

This is Class A (Parent Class)


This is Class B (Child of A)
This is Class C (Child of A)
This is Class D (Child of B and C)

Pure Functions and Modifier Functions:


In Python and other object-oriented programming languages, functions inside a class can be
divided into two types based on how they affect the object’s data:

1. Pure Functions
2. Modifier Functions

These two types help in understanding how data is processed and how the state of an object
changes during program execution.

Pure Function

A pure function is a function that does not modify the object's data.
It only uses the existing value, performs some calculation, and returns the result.

Key Features

 No change to object attributes


 Same input → same output (predictable)
 Does not affect program state
 Used for calculations and value-based opera

Modifier Function

A modifier function is a function that changes or updates the value stored inside the
object.
It modifies the state of the object.

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 11


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

Key Features

 Changes the object’s data


 Does not return a new value (usually returns nothing)
 Updates internal variables
 Used when object state must change

Difference Pure and Modifier Function:

Pure Function Modifier Function


Does not modify object data Modifies object data
Returns a new value Updates the existing value
No side effects Has side effects
Used for calculations Used for updating state
Output does not change next time Output affects future results

Example 1: Pure Function + Modifier Function

class Number:
def __init__(self, value):
[Link] = value

# Pure Function (does NOT change the value)


def double(self):
return [Link] * 2

# Modifier Function (changes the value)


def increase(self, amount):
[Link] = [Link] + amount

# ---------------------------
# Main Program
# ---------------------------

num = Number(10)

# Pure function example


print("Double of value:", [Link]())

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 12


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

# Modifier function example


[Link](5)
print("Value after increasing:", [Link])

Output

Double of value: 20
Value after increasing: 15

Example 2: Bank application

class BankAccount:
def __init__(self, balance):
[Link] = balance

# Pure Function (does NOT modify the balance)


def check_after_deposit(self, amount):
return [Link] + amount

# Modifier Function (changes the balance)


def deposit(self, amount):
[Link] = [Link] + amount

# Modifier Function (changes the balance)


def withdraw(self, amount):
if amount <= [Link]:
[Link] = [Link] - amount
else:
print("Insufficient Balance")

# --- MAIN PROGRAM ---


acc = BankAccount(1000)

print("Initial Balance:", [Link])

# Pure function example


future_balance = acc.check_after_deposit(500)

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 13


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

print("Balance will become (pure function):", future_balance)

# Modifier function examples


[Link](500)
print("Balance after deposit:", [Link])

[Link](300)
print("Balance after withdrawal:", [Link])

Output:

Initial Balance: 1000


Balance will become (pure function): 1500
Balance after deposit: 1500
Balance after withdrawal: 1200

Generalization in Python (OOP)

Definition:
Generalization is the process of extracting common features from two or more classes and
placing them in a single general (parent) class.

 The child classes inherit these common features.


 This avoids code duplication and promotes code reusability.

Example – Bank Accounts

# General Class (Parent)


class Account:

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 14


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

def __init__(self, balance):


[Link] = balance

def deposit(self, amt):


[Link] += amt

def withdraw(self, amt):


if amt <= [Link]:
[Link] -= amt
else:
print("No Money")

# Specific Classes (Child)


class SavingsAccount(Account):
pass

class CurrentAccount(Account):
pass

# --- MAIN ---


s = SavingsAccount(1000)
c = CurrentAccount(2000)

[Link](500)
[Link](300)

print("Savings Account Balance:", [Link])


print("Current Account Balance:", [Link])

Output:

Savings Account Balance: 1500


Current Account Balance: 1700

Polymorphism:

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 15


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

Polymorphism means many forms. In Python, polymorphism allows the same function name,
method, or operator to behave differently depending on the object or data type it is applied to.

Types of Polymorphism in Python

 Method Overloading
 Operator overloading
 Method Overriding (Runtime Polymorphism)

Method Overloading

Method Overloading means having multiple methods with the same name but different
parameters (different number or types of arguments).
It is used to perform similar tasks in different ways.

Example:

Example:

class cal:

def add(self,a,b,c=0):

return(a+b+c)

c=cal()

print([Link](2,3))

print([Link](2.3,5.6))

print([Link](2,7,9))

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 16


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

Method Overriding

Method Overriding is an important feature of Object-Oriented Programming where a child


class provides its own implementation of a method that already exists in the parent class.
The method in the subclass must have the same name, same parameters, and same return
type.

It is used to achieve Runtime Polymorphism (Dynamic Method Dispatch).


The method call is decided at runtime depending on the object’s type, not the reference type.

Method overriding allows subclasses to customize or modify the parent class behavior.
It improves flexibility,and reusability,

Diagram (Simple UML-style)

Shape (Parent)
+ area()
|
---------------------
| |
Circle Rectangle
+ area() + area()

Example Program: Method Overriding in Python

(Finding Area of Circle & Rectangle)

class Shape:
def area(self):
print("Area of shape")

class Circle(Shape):
def area(self): # Overriding
r = 5
print("Area of Circle =", 3.14 * r * r)

class Rectangle(Shape):
def area(self): # Overriding
l = 10
b = 5

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 17


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

print("Area of Rectangle =", l * b)

# Runtime Polymorphism using child class objects


c = Circle()
[Link]()

r = Rectangle()
[Link]()

Output

Area of Circle = 78.5


Area of Rectangle = 50

Difference Between Method Overloading & Overriding

Method Overloading Method Overriding


Same method name, different parameters Same method name, same parameters
Occurs within the same class Occurs between parent & child classes
Compile-time polymorphism (conceptually) Runtime polymorphism
Increases readability Customizes parent class behavior

Operator Overloading

Operator Overloading is an important concept in Object-Oriented Programming (OOP) that


allows *operators such as +, –, , >, <, == to work with user-defined objects just like they
work with built-in data types (int, float, string).

In Python, operator overloading is achieved using special methods (magic methods) that
begin and end with double underscores.

Operator Overloading is the ability to redefine the behavior of an operator so that it


works with objects of user-defined classes. It allows the same operator to have different
meanings based on the operands involved.

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 18


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

Every operator in Python has a corresponding method:

Operator Method Name


+ __add__(self, other)
- __sub__(self, other)
* __mul__(self, other)
/ __truediv__(self, other)
% __mod__(self, other)
< __lt__(self, other)
> __gt__(self, other)
== __eq__(self, other)
!= __ne__(self, other)

When an operator is used between objects, Python automatically calls the appropriate magic
method.

Example:
a + b internally calls → a.__add__(b)

Example 1:

class Number:
def __init__(self, n):
self.n = n

# Overloading + operator
def __add__(self, other):
return self.n + other.n

a = Number(10)
b = Number(20)

print("Sum =", a + b)

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 19


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

Output

Sum = 30

Example 2:

class Value:
def __init__(self, v):
self.v = v

def __add__(self, other):


return self.v + other.v

def __sub__(self, other):


return self.v - other.v

def __mul__(self, other):


return self.v * other.v

x = Value(5)
y = Value(3)

print("Add =", x + y)
print("Sub =", x - y)
print("Mul =", x * y)

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 20


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

Exception Handling:

 An exception is an unexpected event or error that occurs while a program is running.


 It interrupts the normal flow of the program.
 Common causes of exceptions:
o Dividing by zero
o Using undefined variables
o Accessing out-of-range indices
o Converting invalid input
 In Python, every exception is an object derived from the base class Exception

Advantages of Exception Handling

 Prevents the program from crashing due to errors.


 Allows the program to continue running even after an error occurs.
 Provides user-friendly error messages instead of long system errors.
 Helps in debugging by identifying where and why the error occurred.

Handling Exceptions in Python

 try: Contains the code that may cause an error.

 except: Catches and handles the error if it occurs.

 else: Runs only if no error occurs in the try block.

 finally: Runs whether an error occurs or not, often used for cleanup.

 raise: Used to manually trigger an exception..

Python Exceptions

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 21


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

Sl. Exception Name Cause / Meaning Simple


No. Example
1 ZeroDivisionError Occurs when dividing a number by zero 10 / 0
2 ValueError Invalid value for conversion int("abc")
3 TypeError Operation on incompatible data types 5 + "hi"
4 IndexError Using an index outside the list range [1,2,3][5]
5 KeyError Accessing a dictionary key that does not d["age"]
exist
6 NameError Using a variable that is not defined print(x)

Example 1: ZeroDivisionError (Handled)

try:
a = 10
b = 0
print(a / b)

except ZeroDivisionError:
print("Error: Cannot divide a number by zero.")

Example 2: ValueError (Handled)

try:
num = int("abc") # invalid integer

except ValueError:
print("Error: Only numbers can be converted to int.")

Example 3: TypeError (Handled)

Try:

a = 5
b = "hi"
print(a + b)

except TypeError:

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 22


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

print("Error: Cannot add a number and a string.")

Example 4: IndexError (Handled)

try:
nums = [10, 20, 30]
print(nums[5])

except IndexError:
print("Error: Index out of range.")

Example 5: KeyError (Handled)

try:
student = {"name": "John", "age": 20}
print(student["mark"])

except KeyError:
print("Error: Key not found in dictionary.")

Example 6: NameError (Handled)

try:
print(x) # x not defined

except NameError:
print("Error: Variable is not defined.")

Lab 7: Develop a function named DivExp which takes TWO parameters a, b, and returns a
value c (c=a/b). Write a suitable assertion for a>0 in the function DivExp and raise an
exception for when b=0. Develop a suitable program that reads two console values and calls
the function DivExp.

# Function to divide two numbers


def DivExp(a, b):

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 23


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

assert a > 0, "a must be greater than 0" # check a


> 0
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
return a / b

# Main program
a = float(input("Enter a: "))
b = float(input("Enter b: "))

try:
result = DivExp(a, b)
print("Result of a / b is:", result)
except AssertionError as ae:
print(ae)
except ZeroDivisionError as zde:
print(zde)

Raising Your Own Exceptions:

Raising your own exceptions means creating and throwing an exception manually when a
specific error condition occurs in a program. This helps in handling errors clearly and making
programs more robust.

Advantages:

 To handle user-defined error conditions


 To provide meaningful error messages
 To avoid incorrect program execution

Example 1

# Custom exception class


class NegativeNumberError(Exception):
pass

# Main program
num = int(input("Enter a number: "))

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 24


Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data
Science)

if num < 0:
raise NegativeNumberError("Number cannot be negative")

print("You entered:", num)

Example 2

class AgeError(Exception):
pass

try:
age = int(input("Enter age: "))
if age < 18:
raise AgeError("Age must be 18 or above")
print("Eligible")
except AgeError as e:
print(e)

By: Dr. Sunitha Pramod, CSE(Data Science), PESITM Page 25

You might also like