Lab 4
Lab 4
Objective
- To understand the basic concepts of Object-Oriented Programming (OOP) in Python and
implement classes, objects, methods, constructors, method overloading, and inheritance.
Theory
Object-Oriented Programming (OOP) is a way of designing and organizing code using objects and
classes. It helps in building reusable, modular, and scalable programs. The main features of OOP
include:
Code Implementations:
1. Bank account class with deposit and withdrawal.
- class BankAccount:
- def __init__(self, owner, balance=0):
- self.owner = owner
- self.balance = balance
-
- def deposit(self, amount):
- self.balance += amount
- print(f"Deposited: {amount}. New Balance: {self.balance}")
-
- def withdraw(self, amount):
- if amount <= self.balance:
- self.balance -= amount
- print(f"Withdrawn: {amount}. Remaining Balance:
{self.balance}")
- else:
- print("Insufficient balance!")
-
- account = BankAccount("Ram")
- account.deposit(1000)
- account.withdraw(500)
- class Rectangle:
- def __init__(self, length, width):
- self.length = length
- self.width = width
-
- def area(self):
- return self.length * self.width
-
- def perimeter(self):
- return 2 * (self.length + self.width)
-
- rect = Rectangle(5, 3)
- print("Area:", rect.area())
- print("Perimeter:", rect.perimeter())
- class Complex:
- def __init__(self, real, imag):
- self.real = real
- self.imag = imag
-
- def add(self, other):
- return Complex(self.real + other.real, self.imag + other.imag)
-
- def multiply(self, other):
- real = self.real * other.real - self.imag * other.imag
- imag = self.real * other.imag + self.imag * other.real
- return Complex(real, imag)
-
- def display(self):
- print(f"{self.real} + {self.imag}i")
-
- c1 = Complex(2, 3)
- c2 = Complex(1, 4)
-
- sum_result = c1.add(c2)
- prod_result = c1.multiply(c2)
-
- print("Addition:")
- sum_result.display()
-
- print("Multiplication:")
- prod_result.display()
- class Display:
- def show(self, a=None, b=None):
- if a is not None and b is not None:
- print("Two arguments:", a, b)
- elif a is not None:
- print("One argument:", a)
- else:
- print("No arguments")
-
- d = Display()
- d.show()
- d.show(10)
- d.show(10, 20)
5. Inheritance.
- class Person:
- def __init__(self, name):
- self.name = name
-
- def display(self):
- print("Name:", self.name)
-
- class Student(Person):
- def __init__(self, name, roll):
- super().__init__(name)
- self.roll = roll
-
- def display(self):
- super().display()
- print("Roll No:", self.roll)
-
- s = Student("Sita", 101)
- s.display()
Conclusion
This lab helped us understand the principles of Object-Oriented Programming in Python. By
implementing classes, methods, and inheritance, we learned how to write structured and reusable code
using real-world examples like bank accounts, rectangles, and complex numbers.