6. Demonstrate runtime polymorphism using a method play() in a base class Instrument.
Derive
classes Guitar and Piano that implement their own version of play().
class Instrument:
def play(self):
print("This is a Musical Instrument")
class Guitar(Instrument):
def play(self):
print("This is a Guitar")
class Piano(Instrument):
def play(self):
print("This is a Piano")
# Function demonstrating runtime polymorphism
def perform_play(instrument):
instrument.play()
# Calling with different objects
perform_play(Guitar()) # Output: This is a Guitar
perform_play(Piano()) # Output: This is a Piano
7. Create a class MathOperations with a class method add_numbers() to add two numbers and a
static method subtract_numbers() to subtract two numbers.
class MathOperations:
@classmethod
def add_numbers(cls, a, b):
return a + b
@staticmethod
def subtract_numbers(a, b):
return a - b
# Example
print("Addition:", MathOperations.add_numbers(10, 5))
print("Subtraction:", MathOperations.subtract_numbers(10, 5))
8. Implement a class Person with a class method to count the total number of persons created.
class Person:
count = 0
def __init__(self, name):
self.name = name
Person.count += 1
@classmethod
def total_persons(cls):
return cls.count
# Example
p1 = Person("Anand")
p2 = Person("Bhavna")
print("Total Persons Created:", Person.total_persons())
9. Write a class Fraction with attributes numerator and denominator. Override the str method to
display the fraction as 'numerator/denominator'.
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __str__(self):
return f"{self.numerator}/{self.denominator}"
# Example
f1 = Fraction(3, 4)
print(f1)
10. Demonstrate operator overloading by creating a class Vector and overriding the add method to
add two vectors.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"({self.x}, {self.y})"
# Example
v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2
print("v1 + v2 =", v3)
11. Create a class Person with attributes name and age. Add a method greet() that prints the
message.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Example
p = Person("Anand", 25)
p.greet()
12. Implement a class Student with attributes name and grades. Create a method average_grade() to
compute the average.
class Student:
def __init__(self, name, grades):
self.name = name
self.grades = grades
def average_grade(self):
return sum(self.grades) / len(self.grades) if self.grades else 0
# Example
s1 = Student("Anand", [85, 90, 78])
print(f"{s1.name}'s average grade is:", s1.average_grade())
13. Create a class Rectangle with methods set_dimensions() to set the dimensions and area() to
calculate the area.
class Rectangle:
def __init__(self):
self.length = 0
self.breadth = 0
def set_dimensions(self, length, breadth):
self.length = length
self.breadth = breadth
def area(self):
return self.length * self.breadth
# Example
rect = Rectangle()
rect.set_dimensions(10, 5)
print("Area of Rectangle:", rect.area())
14. Create a class Employee with a method calculate_salary() that computes the salary. Create a
derived class Manager that adds a bonus.
class Employee:
def __init__(self, name, hours_worked, hourly_rate):
self.name = name
self.hours_worked = hours_worked
self.hourly_rate = hourly_rate
def calculate_salary(self):
return self.hours_worked * self.hourly_rate
class Manager(Employee):
def __init__(self, name, hours_worked, hourly_rate, bonus):
super().__init__(name, hours_worked, hourly_rate)
self.bonus = bonus
def calculate_salary(self):
return super().calculate_salary() + self.bonus
# Example
m = Manager("Anjali", 45, 300, 5000)
print(f"{m.name}'s Salary:", m.calculate_salary())
15. Create a class Product with attributes name, price, and quantity. Implement a method total_price()
that calculates the total price.
class Product:
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity
def total_price(self):
return self.price * self.quantity
# Example
product = Product("Laptop", 50000, 2)
print("Total price for", product.name, ":", product.total_price())
16. Create a class Animal with an abstract method sound(). Create derived classes Cow and Sheep
that implement sound().
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Cow(Animal):
def sound(self):
print("Cow says Moo")
class Sheep(Animal):
def sound(self):
print("Sheep says Baa")
# Example
Cow().sound()
Sheep().sound()
17. Create a class Book with attributes title, author, and year_published. Add a method
get_book_info().
class Book:
def __init__(self, title, author, year_published):
self.title = title
self.author = author
self.year_published = year_published
def get_book_info(self):
return f"'{self.title}' by {self.author}, published in {self.year_published}"
# Example
b = Book("Wings of Fire", "A.P.J. Abdul Kalam", 1999)
print(b.get_book_info())
18. Create a class House with attributes address and price. Create a derived class Mansion that adds
an attribute number_of_rooms.
class House:
def __init__(self, address, price):
self.address = address
self.price = price
class Mansion(House):
def __init__(self, address, price, number_of_rooms):
super().__init__(address, price)
self.number_of_rooms = number_of_rooms
def show_details(self):
print(f"Address: {self.address}")
print(f"Price: Rs.{self.price}")
print(f"Number of Rooms: {self.number_of_rooms}")
# Example
m = Mansion("Beverly Hills", 100000000, 15)
m.show_details()