Assi. Prof.
MANESH PATEL
PRESIDENT INSTITUTE OF COMPUTER APPLICAION COLLEGE, SHAYONA CAMPUS, A’BAD.
B C A SEM: 5 Practical Python– Unit 3 Python
1 Write a program to create a Student class with a
constructor having more than one parameter. Also
create a method named display() to view the student
details.
class Student:
# Constructor with multiple parameters
def __init__(self, name, roll_no, course):
[Link] = name
self.roll_no = roll_no
[Link] = course
def display(self):
print("Student Details:")
print(f"Name = {[Link]}")
print(f"Roll No = {self.roll_no}")
print(f"Course = {[Link]}")
# Create an object
S1 = Student("Manesh Patel", 10, "BCA")
[Link]()
Student Details:
Name = Manesh Patel
Roll No = 10
Course = BCA
PREPARED BY: PATEL MANESH - [Link](CA & IT) Contact: 90165 17796 1
PATEL MANESH
2 Write a program to demonstrate the use of instance and
class/static variables
class Student:
# Class (Static) Variable
clg_name = "BCA College"
def __init__(self, name, roll_no):
# Instance Variables
[Link] = name
self.roll_no = roll_no
def display(self):
print(f"Name= {[Link]}, Roll No= {self.roll_no}, College= {Student.clg_name}")
# Creating student objects
s1 = Student("Manesh", 11)
s2 = Student("Nivanshi", 20)
[Link]()
[Link]()
print()
print("College Name = ", Student.clg_name)
print()
Student.clg_name = "BBA College"
# Display after modifying the class variable
[Link]()
[Link]()
Name= Manesh, Roll No= 11, College= BCA College
Name= Nivanshi, Roll No= 20, College= BCA College
College Name = BCA College
Name= Manesh, Roll No= 11, College= BBA College
Name= Nivanshi, Roll No= 20, College= BBA College
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 2
PATEL MANESH
3 Write a program to store data into instances using
mutator methods and to retrieve data from the
instances using accessor methods.
class Student:
def __init__(self):
# Private instance variables
[Link] = ""
self.roll_no = 0
# Mutator methods (Setters)
def set_name(self, name):
[Link] = name
def set_roll_no(self, roll_no):
self.roll_no = roll_no
# Accessor methods (Getters)
def get_name(self):
return [Link]
def get_roll_no(self):
return self.roll_no
# Create object of Student
s1 = Student()
# Set data using mutator methods
s1.set_name("Manesh")
s1.set_roll_no(11)
# Get data using accessor methods
print("Student Name:", s1.get_name())
print("Student Roll No:", s1.get_roll_no())
Student Name: Manesh
Student Roll No: 11
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 3
PATEL MANESH
4 Write a program to use class method to handle the
Common features of all the instance of Student class.
class Student:
college_name = "BCA College"
def __init__(self, name, roll_no):
[Link] = name
self.roll_no = roll_no
@classmethod
def update_college(cls, new_college):
cls.college_name = new_college
def display(self):
print("Name= ", [Link])
print("Roll No= ",self.roll_no)
print("College= ", Student.college_name)
print()
# Create objects
s1 = Student("Nidhi", 111)
s2 = Student("Payal", 222) Name= Nidhi
Roll No= 111
[Link]() College= BCA College
[Link]()
Name= Payal
Student.update_college("BBA College") Roll No= 222
College= BCA College
[Link]()
[Link]() Name= Nidhi
Roll No= 111
College= BBA College
Name= payal
Roll No= 222
College= BBA College
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 4
PATEL MANESH
5 Write a program to create a static method that counts
the number of instances created for a class.
class Student:
count = 0 # class variable to count number of objects
def __init__(self):
[Link] = [Link] + 1
def display():
print("Total Objects are created= ", [Link])
s1 = Student()
s2 = Student()
s3 = Student()
s4 = Student()
Total Objects are created= 4
[Link]()
6 Create a Bank class with two variables Name and
Balance. Implement a constructor to initialize the
variable. Also implement deposit and withdrawal using
instance methods
class Bank:
def __init__(self, name, balance):
[Link] = name
[Link] = balance
def deposit(self, amount):
[Link] = [Link] + amount
print("Amount deposited= ", amount)
def withdraw(self, amount):
if amount <= [Link]:
[Link] -= amount
print("Amount withdrawn= ", amount)
print()
else:
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 5
PATEL MANESH
print("sorry.. Not enough balance")
def show(manish):
print("Name= ", [Link])
print("Balance= ", [Link])
print()
# Create an object
acc = Bank("Nivanshi", 1000)
Name= Nivanshi
[Link]() Balance= 1000
# Deposit money Amount deposited= 200
[Link](200) Amount withdrawn= 500
[Link](500) Name= Nivanshi
Balance= 700
7 Create a Student class to with the methods set_id,
get_id, set_name, get_name, set_marks and get_marks
where the method name starting with set are used to
assign the values and method name starting with get are
returning the values. Save the program by [Link].
Create another program to use the Student class which
is already available in [Link].
File Name : [Link]
class Student:
def __init__(self):
self._id = " "
self._name = ""
self._marks = None
def set_id(self, student_id):
self._id = student_id
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 6
PATEL MANESH
def get_id(self):
return self._id
def set_name(self, name):
self._name = name
def get_name(self):
return self._name
def set_marks(self, marks):
self._marks = marks
def get_marks(self):
return self._marks
Another File Name : [Link]
from Student import Student
# Create a student object
s1 = Student()
s1.set_id(11)
s1.set_name("Ashvin Patel")
s1.set_marks(75)
print("Student ID= ", s1.get_id())
print("Student Name= ", s1.get_name())
print("Student Marks= ", s1.get_marks())
Student ID= 11
Student Name= Ashvin Patel
Student Marks= 75
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 7
PATEL MANESH
8 Write a program to access the base class constructor
and method in a sub class by using super().
class Student:
def __init__(self, name, rollno):
[Link] = name
[Link] = rollno
def display(self):
print("Name=", [Link])
print("Roll no=", [Link])
# Subclass
class Child(Student):
def __init__(self, name, rollno):
super().__init__(name, rollno)
def get(self):
super().display()
# Create an object
C = Child("Manish", 50)
[Link]()
Name= Manish
Roll no= 50
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 8
PATEL MANESH
9 Write a program to implement single inheritance in
which two sub classes are derived from a single base
class.
class Person:
def __init__(self, name):
[Link] = name
def show_name(self):
print("Name= ", [Link])
# First subclass
class Doctor(Person):
def __init__(self, name, Degree):
super().__init__(name)
[Link] = Degree
def show(self):
self.show_name()
print("Degree= ", [Link])
# Second subclass
class Engineer(Person):
def __init__(self, name, field):
super().__init__(name)
[Link] = field
def show(self):
self.show_name()
print("Engineering Field= ", [Link])
# Create objects
doc = Doctor("Dr. Vipul", "MBBS")
eng = Engineer("Ashvin", "Copmuter")
print("Doctor Information== ")
[Link]()
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 9
PATEL MANESH
print("\nEngineer Information== ")
[Link]()
Doctor Information==
Name= Dr. Vipul
Degree= MBBS
Engineer Information==
Name= Ashvin
Engineering Field= Computer
10 Write a program to implement multiple inheritance
using two base classes.
# First base class
class Father:
def __init__(self):
self.father_name = "Manish Patel"
# Second base class
class Mother:
def __init__(self):
self.mother_name = "Bina Patel"
# Derived class using multiple inheritance
class Child(Father, Mother):
def __init__(self):
Father.__init__(self)
Mother.__init__(self)
self.child_name = "Nivanshi"
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 10
PATEL MANESH
def show(ABC):
print("Father's Name= ", ABC.father_name)
print("Mother's Name= ", ABC.mother_name)
print("Child's Name= ", ABC.child_name)
# Create object of Child Father's Name= Manish Patel
c = Child()
[Link]() Mother's Name= Bina Patel
Child's Name= Nivanshi
11 Write a program to understand the order of execution of
methods in several base classes according to method
resolution order (MRO)
class A:
def show(self):
print("Method from class A")
class B(A):
def show(self):
print("Method from class B")
class C(A):
def show(self):
print("Method from class C")
class D(B, C):
pass
# def show(self):
# print("Method from class D"))
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 11
PATEL MANESH
d = D()
[Link]()
# Print MRO
print("Method Resolution Order (MRO) = ")
for manish in D.__mro__:
print(manish)
Method from class B
Method Resolution Order (MRO) =
<class '__main__.D'>
<class '__main__.B'>
<class '__main__.C'>
<class '__main__.A'>
<class 'object'>
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 12
PATEL MANESH
12 Write a program to check the object type to know
whether the method exists in the object or not.
class Student:
def study(self):
print("Student is studying")
class Teacher:
def teach(self):
print("Teacher is teaching")
# Create objects
s = Student()
t = Teacher()
# Check if the method 'study' exists in Student object
if hasattr(s, 'study'):
print("Method 'study' exists in Student object.")
[Link]()
else:
print("Method 'study' does NOT exist in Student object.")
# Check if the method 'teach' exists in Student object
if hasattr(s, 'teach'):
print("Method 'teach' exists in Student object.")
[Link]()
else:
print("Method 'teach' does NOT exist in Student object.")
Method 'study' exists in Student object.
Student is studying
Method 'teach' does NOT exist in Student object.
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 13
PATEL MANESH
13 Write a program to overload the addition operator (+) to
make it act on the class objects.
class Addition:
def __init__(self, x, y):
self.p = x
self.q = y
# Overloading the + operator
def __add__(self, other):
return Addition(self.p + other.p, self.q + other.q)
def display(self):
print("X (10 + 30) = ", self.p)
print("Y (20 + 40)= ", self.q)
# Create two Point objects
A1 = Addition(10, 20)
A2 = Addition(30, 40)
# Add them using + operator
A3 = A1 + A2
# Display the result
[Link]() X (10 + 30) = 40
Y (20 + 40)= 60
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 14
PATEL MANESH
14 Write a program to show method overloading to find
sum of two or three numbers.
class Demo:
def addition(self, *args):
return sum(args)
D = Demo()
print("Sum of Two Numbers= ", [Link](5, 10))
print("Sum of Three Numbers= ", [Link](50, 100, 50))
print("Sum of Four Numbers= :", [Link](10, 20, 30, 40))
Sum of Two Numbers= 15
Sum of Three Numbers= 200
Sum of Four Numbers= : 100
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 15
PATEL MANESH
15 Write a program to override the super class method in
Subclass
class Father:
def show(self):
print("I am from Father Class")
class Child(Father):
def show(self):
#super().show()
print("I am from Child Class")
F = Father() I am from Father Class
C = Child()
I am from Child Class
[Link]()
[Link]()
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 16
PATEL MANESH
16 Write a program to handle some built in exceptions like
ZeroDivisionError.
try:
a = int(input("Enter No1= "))
b = int(input("Enter No2= "))
# Division operation
result = a / b
print("Result = ", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Please enter valid integers only.")
except Exception as e:
print("An unexpected error occurred:", e)
finally:
print("Execution completed.")
Enter No1= 10
Enter No2= 2
Result = 5.0
Execution completed.
Enter No1= 10
Enter No2= 0
Error: Cannot divide by zero.
Execution completed.
Enter No1= 50
Enter No2= manish
Error: Please enter valid integers only.
Execution completed.
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 17
PATEL MANESH
17 Write a program to handle multiple exceptions.
(Same as Above Program)
try:
a = int(input("Enter No1= "))
b = int(input("Enter No2= "))
# Division operation
result = a / b
print("Result = ", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Please enter valid integers only.")
except Exception as e:
print("An unexpected error occurred:", e)
finally:
print("Execution completed.")
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 18