0% found this document useful (0 votes)
2 views

Python Lab Assignment 4

lab work of python

Uploaded by

kaurmultani222
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Lab Assignment 4

lab work of python

Uploaded by

kaurmultani222
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Python Lab Assignment : 4

Program 1: Basic Class and Object Creation


Task:
1. Create a Rectangle class with attributes length and
breadth.
2. Add methods to calculate and return the area and
perimeter.
3. Write a script to create an object of Rectangle, set its
attributes, and display the area and perimeter.
Program:
class Rectangle:

# Constructor to initialize the attributes

def __init__(self, length=1, breadth=1):

self.length = length

self.breadth = breadth

# Method to calculate area

def calculate_area(self):

return self.length * self.breadth

# Method to calculate perimeter

def calculate_perimeter(self):

return 2 * (self.length + self.breadth)

# Script to create a Rectangle object

if __name__ == "__main__":
# Create an object of the Rectangle class

rect = Rectangle()

# Set attributes

rect.length = float(input("Enter the length of the rectangle: "))

rect.breadth = float(input("Enter the breadth of the rectangle: "))

# Display area and perimeter

print(f"Area of the rectangle: {rect.calculate_area()}")

print(f"Perimeter of the rectangle: {rect.calculate_perimeter()}")

Output:

Program 2: Constructor and Instance Methods


Task:
1. Create a Student class with attributes name,
roll_number, and marks.
2. Add a constructor to initialize these attributes.
3. Add a method to display student details.
4. Create multiple student objects and display their
details.
Program:
class Student:
# Constructor to initialize the attributes
def __init__(self, name, roll_number, marks):
self.name = name
self.roll_number = roll_number
self.marks = marks

# Method to display student details


def display_details(self):
print(f"Name: {self.name}")
print(f"Roll Number: {self.roll_number}")
print(f"Marks: {self.marks}")
print("-" * 30)

# Script to create multiple Student objects and display their


details
if __name__ == "__main__":
# Create a list to store student objects
students = []

# Number of students
n = int(input("Enter the number of students: "))
# Create student objects and add them to the list
for i in range(n):
print(f"\nEnter details for student {i + 1}:")
name = input("Name: ")
roll_number = input("Roll Number: ")
marks = float(input("Marks: "))
student = Student(name, roll_number, marks)
students.append(student)

# Display details of all students


print("\nStudent Details:")
for student in students:
student.display_details()

Output:
Program 3: Inheritance
Task:
1. Create a Person class with attributes name and age.
2. Create a subclass Employee that inherits from Person
and adds an attribute salary.
3. Add a method in Employee to display all details.
4. Create an Employee object and demonstrate
inheritance
Program:
# Base class: Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Subclass: Employee
class Employee(Person):
def __init__(self, name, age, salary):
# Call the constructor of the parent class
super().__init__(name, age)
self.salary = salary

# Method to display employee details


def display_details(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
print(f"Salary: {self.salary}")

# Script to demonstrate inheritance


if __name__ == "__main__":
# Create an Employee object
emp_name = input("Enter employee's name: ")
emp_age = int(input("Enter employee's age: "))
emp_salary = float(input("Enter employee's salary: "))

employee = Employee(emp_name, emp_age, emp_salary)

# Display employee details


print("\nEmployee Details:")
employee.display_details()
Output:

Program 4: Multiple Inheritance


Task:
1. Create two classes Mother and Father with methods
traits to describe their specific characteristics.
2. Create a Child class that inherits from both Mother
and Father.
3. Use the Child class to display combined traits.
Program:
# Base class: Mother
class Mother:
def traits(self):
return "Kind and caring"

# Base class: Father


class Father:
def traits(self):
return "Strong and wise"

# Subclass: Child
class Child(Mother, Father):
def combined_traits(self):
return f"Mother's traits: {Mother.traits(self)}\nFather's
traits: {Father.traits(self)}"

# Script to demonstrate multiple inheritance


if __name__ == "__main__":
# Create an object of the Child class
child = Child()

# Display combined traits


print("Child's inherited traits:")
print(child.combined_traits())

Output:
Program 5: Operator Overloading
Task:
1. Create a ComplexNumber class with attributes real
and imaginary.
2. Overload the + operator to add two complex
numbers.
3. Overload the __str__ method to display a complex
number in the form a + bi.
4. Write a script to demonstrate operator overloading
with this class.
Program:
class ComplexNumber:
# Constructor to initialize the real and imaginary parts
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
# Overloading the + operator
def __add__(self, other):
if isinstance(other, ComplexNumber):
return ComplexNumber(self.real + other.real,
self.imaginary + other.imaginary)
raise TypeError("Operands must be instances of
ComplexNumber")

# Overloading the __str__ method to display complex


numbers in a + bi format
def __str__(self):
return f"{self.real} + {self.imaginary}i"

# Script to demonstrate operator overloading


if __name__ == "__main__":
# Create two complex numbers
real1 = float(input("Enter the real part of the first complex
number: "))
imag1 = float(input("Enter the imaginary part of the first
complex number: "))
real2 = float(input("Enter the real part of the second
complex number: "))
imag2 = float(input("Enter the imaginary part of the second
complex number: "))

num1 = ComplexNumber(real1, imag1)


num2 = ComplexNumber(real2, imag2)

# Add the two complex numbers


result = num1 + num2

# Display the results


print("\nFirst complex number:", num1)
print("Second complex number:", num2)
print("Sum of the two complex numbers:", result)
Output:

Program 6: Class Variables and Instance Variables


Task:
1. Create a BankAccount class with attributes
account_number, balance, and a class variable
bank_name.
2. Add methods to deposit and withdraw money.
3. Demonstrate the difference between instance and
class variables using this class.
Program:
class BankAccount:
# Class variable
bank_name = "Global Bank"

# Constructor to initialize account-specific attributes


def __init__(self, account_number, balance=0.0):
self.account_number = account_number # Instance
variable
self.balance = balance # Instance variable

# Method to deposit money


def deposit(self, amount):
if amount > 0:
self.balance += amount
print(f"Deposited {amount:.2f}. New balance:
{self.balance:.2f}")
else:
print("Deposit amount must be positive.")

# Method to withdraw money


def withdraw(self, amount):
if 0 < amount <= self.balance:
self.balance -= amount
print(f"Withdrew {amount:.2f}. New balance:
{self.balance:.2f}")
elif amount > self.balance:
print("Insufficient balance.")
else:
print("Withdrawal amount must be positive.")

# Method to display account details


def display_account_details(self):
print(f"Bank: {BankAccount.bank_name}")
print(f"Account Number: {self.account_number}")
print(f"Balance: {self.balance:.2f}")

# Script to demonstrate class and instance variables


if __name__ == "__main__":
# Create two bank accounts
account1 = BankAccount("123456", 1000)
account2 = BankAccount("789012", 500)

# Display initial account details


print("\nAccount 1 Details:")
account1.display_account_details()

print("\nAccount 2 Details:")
account2.display_account_details()
# Perform transactions on account1
print("\nTransactions for Account 1:")
account1.deposit(500)
account1.withdraw(300)

# Perform transactions on account2


print("\nTransactions for Account 2:")
account2.deposit(200)
account2.withdraw(800)

# Show the class variable remains consistent


print("\nDemonstrating Class Variable:")
print(f"Bank Name (Account 1): {account1.bank_name}")
print(f"Bank Name (Account 2): {account2.bank_name}")
print(f"Bank Name (Accessed via Class):
{BankAccount.bank_name}")
Output:
Program 7: Static Methods and Class Methods
Task:
1. Create a MathUtils class with:
o A static method to calculate the factorial of a number.
o A class method to return the class name.
2. Demonstrate the use of both methods.
Program:
class MathUtils:
# Static method to calculate factorial
@staticmethod
def factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers."
result = 1
for i in range(1, n + 1):
result *= i
return result

# Class method to return the class name


@classmethod
def get_class_name(cls):
return cls.__name__

# Script to demonstrate static and class methods


if __name__ == "__main__":
# Demonstrate the static method
num = int(input("Enter a number to calculate its factorial: "))
print(f"Factorial of {num}: {MathUtils.factorial(num)}")

# Demonstrate the class method


print(f"Class Name: {MathUtils.get_class_name()}")
Output:
Program 8: Polymorphism
Task:
1. Create a base class Animal with a method sound that
prints "Some sound".
2. Create subclasses Dog and Cat that override the
sound method to print specific sounds.
3. Write a function that takes an Animal object and calls
its sound method. Demonstrate polymorphism with it.
Program:
# Base class: Animal
class Animal:
def sound(self):
print("Some sound")

# Subclass: Dog
class Dog(Animal):
def sound(self):
print("Bark")

# Subclass: Cat
class Cat(Animal):
def sound(self):
print("Meow")

# Function to demonstrate polymorphism


def make_sound(animal):
animal.sound()

# Script to demonstrate polymorphism


if __name__ == "__main__":
# Create instances of Dog and Cat
dog = Dog()
cat = Cat()

# Demonstrate polymorphism
print("Dog:")
make_sound(dog) # Calls Dog's sound method

print("\nCat:")
make_sound(cat) # Calls Cat's sound method

print("\nGeneric Animal:")
generic_animal = Animal()
make_sound(generic_animal) # Calls Animal's sound
method

Output:

You might also like