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

Python Practical Unit 3 Final

The document contains a series of Python programming exercises focused on object-oriented programming concepts such as classes, inheritance, method overloading, and instance variables. Each exercise includes code examples demonstrating the implementation of various features like constructors, mutator/accessor methods, class methods, and operator overloading. The document is prepared by Assi. Prof. Manesh Patel for a BCA practical course.

Uploaded by

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

Python Practical Unit 3 Final

The document contains a series of Python programming exercises focused on object-oriented programming concepts such as classes, inheritance, method overloading, and instance variables. Each exercise includes code examples demonstrating the implementation of various features like constructors, mutator/accessor methods, class methods, and operator overloading. The document is prepared by Assi. Prof. Manesh Patel for a BCA practical course.

Uploaded by

Manesh Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

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):
self.name = name
self.roll_no = roll_no
self.course = course

def display(self):
print("Student Details:")
print(f"Name = {S1.name}")
print(f"Roll No = {self.roll_no}")
print(f"Course = {S1.course}")

# Create an object
S1 = Student("Manesh Patel", 10, "BCA")

S1.display()

Student Details:
Name = Manesh Patel
Roll No = 10
Course = BCA

PREPARED BY: PATEL MANESH - M.Sc(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
self.name = name
self.roll_no = roll_no

def display(self):
print(f"Name= {self.name}, Roll No= {self.roll_no}, College= {Student.clg_name}")

# Creating student objects


s1 = Student("Manesh", 11)
s2 = Student("Nivanshi", 20)

s1.display()
s2.display()

print()
print("College Name = ", Student.clg_name)
print()

Student.clg_name = "BBA College"

# Display after modifying the class variable


s1.display()
s2.display()

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 - M.Sc(CA & IT), B.ED 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
self.name = ""
self.roll_no = 0

# Mutator methods (Setters)


def set_name(self, name):
self.name = name

def set_roll_no(self, roll_no):


self.roll_no = roll_no

# Accessor methods (Getters)


def get_name(self):
return self.name

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 - M.Sc(CA & IT), B.ED 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):


self.name = name
self.roll_no = roll_no

@classmethod
def update_college(cls, new_college):
cls.college_name = new_college

def display(self):
print("Name= ", self.name)
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
s1.display() College= BCA College
s2.display()
Name= Payal
Student.update_college("BBA College") Roll No= 222
College= BCA College
s1.display()
s2.display() Name= Nidhi
Roll No= 111
College= BBA College

Name= payal
Roll No= 222
College= BBA College

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED 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):
Student.count = self.count + 1

def display():
print("Total Objects are created= ", Student.count)

s1 = Student()
s2 = Student()
s3 = Student()
s4 = Student()
Total Objects are created= 4
Student.display()

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):
self.name = name
self.balance = balance

def deposit(self, amount):


self.balance = self.balance + amount
print("Amount deposited= ", amount)

def withdraw(self, amount):


if amount <= self.balance:
self.balance -= amount
print("Amount withdrawn= ", amount)
print()
else:
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 5
PATEL MANESH

print("sorry.. Not enough balance")

def show(manish):
print("Name= ", manish.name)
print("Balance= ", manish.balance)
print()

# Create an object
acc = Bank("Nivanshi", 1000)
Name= Nivanshi
acc.show() Balance= 1000

# Deposit money Amount deposited= 200


acc.deposit(200) Amount withdrawn= 500

acc.withdraw(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 student.py.
Create another program to use the Student class which
is already available in student.py.

File Name : Student.py

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 - M.Sc(CA & IT), B.ED 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 : Jay.py

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 - M.Sc(CA & IT), B.ED 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):
self.name = name
self.rollno = rollno

def display(self):
print("Name=", self.name)
print("Roll no=", self.rollno)

# 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)
C.get()

Name= Manish
Roll no= 50

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED 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):
self.name = name

def show_name(self):
print("Name= ", self.name)

# First subclass
class Doctor(Person):
def __init__(self, name, Degree):
super().__init__(name)
self.Degree = Degree

def show(self):
self.show_name()
print("Degree= ", self.Degree)

# Second subclass
class Engineer(Person):
def __init__(self, name, field):
super().__init__(name)
self.field = field

def show(self):
self.show_name()
print("Engineering Field= ", self.field)

# Create objects
doc = Doctor("Dr. Vipul", "MBBS")
eng = Engineer("Ashvin", "Copmuter")

print("Doctor Information== ")


doc.show()

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 9
PATEL MANESH

print("\nEngineer Information== ")


eng.show()
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 - M.Sc(CA & IT), B.ED 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()
c.show() 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 - M.Sc(CA & IT), B.ED Contact: 90165 17796 11
PATEL MANESH

d = D()
d.show()

# 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 - M.Sc(CA & IT), B.ED 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.")
s.study()
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.")
s.teach()
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 - M.Sc(CA & IT), B.ED 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


A3.display() X (10 + 30) = 40
Y (20 + 40)= 60

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED 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= ", D.addition(5, 10))

print("Sum of Three Numbers= ", D.addition(50, 100, 50))

print("Sum of Four Numbers= :", D.addition(10, 20, 30, 40))

Sum of Two Numbers= 15


Sum of Three Numbers= 200
Sum of Four Numbers= : 100

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED 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
F.show()
C.show()

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED 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 - M.Sc(CA & IT), B.ED 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 - M.Sc(CA & IT), B.ED Contact: 90165 17796 18

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy