0% found this document useful (0 votes)
2 views11 pages

Unit 2 Lab Programs Corrected

The document outlines various object-oriented programming concepts in Python, including polymorphism, encapsulation, data abstraction, inheritance, method overloading, and method overriding. It provides detailed algorithms and example programs for each concept, demonstrating their implementation and results. Additionally, it includes an example of creating a module for mathematical operations using a calculator class.

Uploaded by

avkk75
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)
2 views11 pages

Unit 2 Lab Programs Corrected

The document outlines various object-oriented programming concepts in Python, including polymorphism, encapsulation, data abstraction, inheritance, method overloading, and method overriding. It provides detailed algorithms and example programs for each concept, demonstrating their implementation and results. Additionally, it includes an example of creating a module for mathematical operations using a calculator class.

Uploaded by

avkk75
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/ 11

Unit -2

OBJECT ORIENTED CONCEPTS

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.

Aim: Program to illustrate polymorphism


Algorithm:
Step1: create a class named rectangle
Step2: Input length and breadth
Step3: create a function area
Step4: calculate area =length x breadth
Step5: return the value area
Step6: create a class square
Step7: Input side value
Step8: create a function area
Step9: calculate area =side x side
Step10: return the value area

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

Result: The python program using polymorphism was implemented successfully.

----------------------------------------------------------------------------------------------------

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.

Aim: Program to illustrate Encapsulation


Algorithm:
Step 1: create class car
Step 2: declare a variable a
Step 3: declare a variable double underscore c
Step 4: assign a= steering
Step 5: assign c=engine
Step 6: create a object ob1 for class car
Step 7: access the variable a
Step 8: access the variable double underscore c

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.

----------------------------------------------------------------------------------------------------

Exp 2.2a) Implement Data Abstraction and Inheritance.

Aim: Program to illustrate Data Abstraction

Algorithm:

1.​ Import Required Modules:


o​ Import ABC and abstractmethod from the abc module to implement an abstract base
class.
2.​ Define Abstract Base Class:
o​ Create a class named llgm that inherits from ABC.
o​ Define an abstract method calculate_area using the @abstractmethod decorator. This
method does not have an implementation.
3.​ Define the Square Class:
o​ Create a class named Square that inherits from llgm.
o​ Add a class-level attribute length and set it to 5.
o​ Implement the calculate_area method to calculate the area of a square as length *
length.
4.​ Define the Circle Class:
o​ Create a class named Circle that inherits from llgm.
o​ Add a class-level attribute radius and set it to 4.
o​ Implement the calculate_area method to calculate the area of a circle using the
formula 3.14 * radius * radius.

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

# Creating objects for the classes


sq = Square()
cir = Circle()

# 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

Result: The Python Program to implement Data Abstraction has been


executed successfully.
-----------------------------------------------------------------------------

Exp 2.2b
Aim: Program to implement Inheritance

Algorithm:

1.​ Import Required Modules:


o​ Import ABC and abstractmethod from the abc module to define an abstract base class.
2.​ Define Abstract Base Class:
o​ Create a class named Bank that inherits from ABC.
o​ Define a method bank_info to display general information about the bank. This is a
concrete method (not abstract).
o​ Define an abstract method interest using the @abstractmethod decorator. This method
does not have an implementation and must be implemented by any subclass.
3.​ Define Subclass SBI:
o​ Create a class named SBI that inherits from the Bank class.
o​ Implement the abstract method interest by defining it in the SBI class. Print "In SBI
bank 5 rupees interest" inside this method.
4.​ Create an Instance of the SBI Class:
o​ Create an object s of the SBI class.
5.​ Call the Methods:
o​ Call the bank_info method on the SBI object s to display the general bank
information.
o​ Call the interest method on the SBI object s to display the specific interest
information.

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

Result: The Python program to implement Inheritance has been executed


successfully.

--------------------------------------------------------------------------------------------

Exp :2.3 Differentiate Method Overloading and Overriding.

Aim: To Differentiate Method Overloading and Overriding.


Algorithm:
Method Overloading:

1) We create a class with one method sayHello().


2) The first parameter of this method is set to None.
3) This gives us the option to call it with or without a parameter.
4) An object is created based on the class
5) we call its method using zero and one parameter.
6) To clarify method overloading, we can now call the method sayHello() in two ways:
i)obj.sayHello()
ii)obj.sayHello('cse')

program:

6
class Human:

def sayHello(self, name=None):

if name is not None:


print('Hello ' + name)
else:
print('Hello ')

# Create instance
obj = Human()

# Call the method


obj.sayHello()

# Call the method with a parameter


obj.sayHello('cse')

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.

Ex. No. 2.4

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:

1.​ Define the Class:Create a class named Person.


2.​ Initialize the Constructor:Define the __init__ method with two parameters: name and
age.Assign the name parameter to the public instance attribute self.name.Assign the age
parameter to the private instance attribute self.__age (using a double underscore to make it
private).
3.​ Define a Getter Method: Create a method named get_age. In the method, return the
private attribute self.__age.
4.​ Create an Instance of the Class:Instantiate the Person class with the name "John" and age
25, storing the object in the variable person.
5.​ Access and Print Public Attribute: Access the name attribute of the person object directly
and print it.
6.​ Access and Print Private Attribute via Getter Method:Call the get_age method of the
person object to retrieve the private __age attribute and print it.

Program:
class Person:

8
def __init__(self, name, age):
self.name = name
self.__age = age # Private attribute

# Getter method to access the private 'age' attribute


def get_age(self):
return self.__age

# Create an instance of the Person class


person = Person("John", 25)

# Accessing the public attribute 'name'


print("Name:", person.name)

# Accessing the private attribute 'age' using the getter method


print("Age:", person.get_age())

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!

Result : Python program to implement a “calculator” has been executed successfully.

11

You might also like