Unit 2 Lab Programs Corrected
Unit 2 Lab Programs Corrected
Exp 2.1a) The floor of the white house consists of many squares and rectangle.
Tom wants to name single function of different perspective to calculate the area of
squares and rectangle. Help tom to achieve his objective by means of
polymorphism.
Program:
class Rectangle:
def __init__(self, length, breadth):
self.l = length
self.b = breadth
def area(self):
return self.l * self.b
class Square:
def __init__(self, side):
self.s = side
def area(self):
return self.s ** 2
rec = Rectangle(5, 20)
1
squ = Square(9)
print("Area of rectangle is: ", rec.area())
print("Area of square is: ", squ.area())
output
Area of rectangle is: 100
Area of square is: 81
----------------------------------------------------------------------------------------------------
Exp 2.1b) Imagine a car. Its components such as steering, wheel, brake, accelerator
are all visible and can be accessed directly. Car engine was encapsulated so that we
can’t access it freely. Image these real time circumstances develop a python
program to perform the concept of encapsulation.
Program:
# program to implement encapsulation
class car:
def __init__(self):
self.a = "steering-accessing normal variable"
self.__c = "engine" #double underscore before the variable makes it as private
obj1 = car()
2
print(obj1.a)
print("try to access private variable but is shows............error as")
print(obj1.__c) # try to access private variable
Output:
steering-accessing normal variable
try to access private variable but is shows............error as
Traceback (most recent call last):
File "<string>", line 10, in <module>
ERROR!
AttributeError: 'car' object has no attribute '__c'
Result: The python program for implementing Encapsulation has been executed
successfully.
----------------------------------------------------------------------------------------------------
Algorithm:
3
5. Create Instances of Subclasses:
o Create an instance of the Square class and store it in the variable sq.
o Create an instance of the Circle class and store it in the variable cir.
6. Call Methods to Calculate Area:
o Call the calculate_area method on the sq object to calculate the area of the square.
o Call the calculate_area method on the cir object to calculate the area of the circle.
7. Print the Results:
o Print the calculated area of the square.
o Print the calculated area of the circle.
Program:
from abc import ABC, abstractmethod
class llgm(ABC):
@abstractmethod
def calculate_area(self):
pass
class Square(llgm):
length = 5
def calculate_area(self):
return self.length * self.length
class Circle(llgm):
radius = 4
def calculate_area(self):
return 3.14 * self.radius * self.radius
# Printing areas
print("Area of a Square:", sq.calculate_area())
print("Area of a Circle:", cir.calculate_area())
Output:
4
Area of a Square: 25
Area of a Circle: 50.24
Exp 2.2b
Aim: Program to implement Inheritance
Algorithm:
Program
from abc import ABC, abstractmethod
#Abstract Class
class Bank(ABC):
def bank_info(self):
print("Welcome to bank")
@abstractmethod
def interest(self):
5
"Abstract Method"
pass
#Sub class/ child class of abstract class
class SBI(Bank):
def interest(self):
"Implementation of abstract method"
print("In sbi bank 5 rupees interest")
s= SBI()
s.bank_info ()
s.interest()
Output:
Welcome to bank
In sbi bank 5 rupees interest
--------------------------------------------------------------------------------------------
program:
6
class Human:
# Create instance
obj = Human()
output:
Hello
Hello cse
ALGORITHM
Method overriding:
1) created an employee class which contains a message function that prints a message.
2) Next, we created a department that inherits from the Employee class.
3) Within this, we created a function with the same name message with a different print message.
4) Here, we are just overriding the message. Next, we created an Object for Employee and Department
class and calling that message function.
5) The emp object is printing a string from the Employee message function. Whereas dept.message() is a
printing test from Department.
Program:
class Employee:
def message(self):
print('This message is from Emp')
class Department(Employee):
def message(self):
7
print('This Department is inherited from Emp')
emp = Employee()
emp.message()
print('------------')
dept = Department()
dept.message()
output:
This message is from Emp
------------
This Department is inherited from Emp
Result : Python program for method Overloading and Method Overriding has been executed
successfully.
Create a class called "Person" with attributes "name" and "age". Make the "age" attribute private
and implement a getter method to access it.
Aim: To Create a class called "Person" with attributes "name" and "age". Make the "age" attribute private
and implement a getter method to access it.
Algorithm:
Program:
class Person:
8
def __init__(self, name, age):
self.name = name
self.__age = age # Private attribute
Output:
Name: John
Age: 25
Result: Python program for creating a class and accessing its method was executed successfully.
EX.No.2.5
Aim:
Create a module called "math_operations.py" with a class called "Calculator." Import the
"Calculator" class into another script and use its methods to perform mathematical operations..
Algorithm
1: A module can contain functions, classes, and variables that can be used in other parts of your
program.
2: In , the module “math_operations.py” contains a function called “add”
,”Sub”,”multiply”,divide…etc and a class called “calc”. These can be imported and used in other
Python scripts with the class calc().
3: Use the add() function to work with values assigned to the function in Python
4: Before use the methods , need to import the module first using import command
5: Run the code and execute the output
Program
9
# import math_operations.py
class calculator():
def __init__(self,a,b):
self.a=a
self.b=b
def add(self):
return self.a+self.b
def mul(self):
return self.a*self.b
def div(self):
return self.a/self.b
def sub(self):
return self.a-self.b
#from math_operations.py import add, mul, div , sub
a=int(input("Enter first number: "))
b=int(input("Enter second number: "))
obj=calculator(a,b)
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice=int(input("Enter choice: "))
if choice==1:
print("Result: ",obj.add())
elif choice==2:
print("Result: ",obj.sub())
elif choice==3:
print("Result: ",obj.mul())
elif choice==4:
print("Result: ",round(obj.div(),2))
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print()
Output
10
Enter first number: 12
Enter second number: 12
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 1
Result: 24
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 2
Result: 0
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 3
Result: 144
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 4
Result: 1.0
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 0
Exiting!
11