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

Python Module 5 Answers

Uploaded by

roshannayar3
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 views29 pages

Python Module 5 Answers

Uploaded by

roshannayar3
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

Module-5:

1. Define inheritance in Python. Explain how a derived class inherits attributes


and methods from a base class with a suitable example.

Inheritance in Python

Inheritance is an Object-Oriented Programming (OOP) feature that allows one


class (called the derived class or child class) to acquire the properties and
behaviors (attributes and methods) of another class (called the base class or parent
class).

Syntax:

class BaseClass:
# attributes and methods

class DerivedClass(BaseClass):
# additional attributes and methods

The derived class automatically inherits all accessible attributes and methods of the
base class and can also add new features or override existing methods.

# Base Class
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

def display(self):
print("Name:", [Link])
print("Age:", [Link])

# Derived Class
class Student(Person):
def __init__(self, name, age, roll_no):
# Calling constructor of base class
super().__init__(name, age)
self.roll_no = roll_no

def show_roll(self):
print("Roll Number:", self.roll_no)

# Creating object of derived class


s = Student("Rahul", 20, 101)

# Accessing inherited method


[Link]()

# Accessing derived class method


s.show_roll()

2. Explain the syntax for defining a subclass in Python. How is the parent class
constructor invoked using super()? Give an example.

Subclass Definition Syntax

A subclass (derived class) is a class that inherits the properties and methods of
another class called the parent class (base class).

Syntax:

class ParentClass:
# Parent class members

class ChildClass(ParentClass):
# Child class members

Invoking the Parent Class Constructor Using super()

When a subclass defines its own constructor (__init__()), it can call the parent
class constructor using the super() function.

super().__init__(arguments)
super() returns a temporary object of the parent class.
__init__() invokes the parent class constructor.
This ensures that the parent class attributes are initialized properly.
# Parent Class
class Employee:
def __init__(self, name, salary):
[Link] = name
[Link] = salary

def display_employee(self):
print("Employee Name:", [Link])
print("Salary:", [Link])

# Subclass
class Manager(Employee):
def __init__(self, name, salary, department):
# Calling parent class constructor
super().__init__(name, salary)
[Link] = department
def display_manager(self):
print("Department:", [Link])

# Creating object of subclass


m = Manager("Ravi", 50000, "HR")

# Accessing inherited method


m.display_employee()

# Accessing subclass method


m.display_manager()

3. What is single inheritance? Write a Python program to implement single


inheritance with a Person and Student class.

Single Inheritance in Python

Single Inheritance is a type of inheritance in which a derived class inherits from


only one base class. The derived class acquires all the attributes and methods of the
parent class and can also define its own additional attributes and methods.

Person (Base Class)




Student (Derived Class)

Example:

# Base Class
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

def display_person(self):
print("Name:", [Link])
print("Age:", [Link])

# Derived Class
class Student(Person):
def __init__(self, name, age, roll_no):
# Call parent class constructor
super().__init__(name, age)
self.roll_no = roll_no

def display_student(self):
print("Roll Number:", self.roll_no)

# Creating object of Student class


s = Student("Rahul", 20, 101)

# Accessing inherited method


s.display_person()

# Accessing Student class method


s.display_student()

4. Explain multilevel inheritance in Python with a suitable example involving three


levels of classes.

Multilevel Inheritance in Python

Multilevel Inheritance is a type of inheritance in which a class inherits from


another derived class, forming a chain of inheritance. In other words, a derived
class becomes the base class for another class.

Grandparent Class


Parent Class


Child Class

The child class inherits the properties and methods of both the parent class and the
grandparent class.

# Grandparent Class
class Person:
def __init__(self, name):
[Link] = name

def display_name(self):
print("Name:", [Link])

# Parent Class
class Student(Person):
def __init__(self, name, roll_no):
super().__init__(name)
self.roll_no = roll_no

def display_roll(self):
print("Roll Number:", self.roll_no)

# Child Class
class GraduateStudent(Student):
def __init__(self, name, roll_no, specialization):
super().__init__(name, roll_no)
[Link] = specialization

def display_specialization(self):
print("Specialization:", [Link])

# Creating object of GraduateStudent


g = GraduateStudent("Rahul", 101, "Structural Engineering")

# Accessing methods from all levels


g.display_name()
g.display_roll()
g.display_specialization()

5. Describe multiple inheritance in Python. What is the Method Resolution Order


(MRO)? Illustrate with an example.

Multiple Inheritance is a type of inheritance in which a class inherits attributes and


methods from more than one parent class.

This allows a derived class to combine the features of multiple base classes.

class Parent1:
pass

class Parent2:
pass

class Child(Parent1, Parent2):


pass

Method Resolution Order (MRO)

When multiple inheritance is used, two or more parent classes may contain
methods with the same name. Python needs a rule to determine which method
should be called first.
The Method Resolution Order (MRO) is the order in which Python searches
classes for a method or attribute.

Python follows the C3 Linearization Algorithm to determine this order.

class A:
def display(self):
print("Method from Class A")

class B:
def display(self):
print("Method from Class B")

class C(A, B):


pass

obj = C()
[Link]()

6. Explain the role of the super() function in inheritance. How is it used to call the
parent class method from a child class? Give an example.

Role of super() Function in Inheritance

The super() function in Python is used to access the methods and constructors of
the parent (base) class from a child (derived) class.

It helps avoid rewriting code and ensures that the parent class is properly initialized
when inheritance is used.

Calling Parent Class Constructor


super().__init__(arguments)
Calling Parent Class Method
super().method_name()
# Parent Class
class Person:
def __init__(self, name):
[Link] = name
print("Person constructor called")

def display(self):
print("Name:", [Link])

# Child Class
class Student(Person):
def __init__(self, name, roll_no):
# Calling Parent Class Constructor
super().__init__(name)
self.roll_no = roll_no

def show_details(self):
# Calling Parent Class Method
super().display()
print("Roll Number:", self.roll_no)

# Creating Object
s = Student("Rahul", 101)

# Calling Child Class Method


s.show_details()

7. What is method overriding in Python? Differentiate it from method overloading.


Give an example of method overriding.

Method Overriding is an Object-Oriented Programming (OOP) concept in which a


child class provides its own implementation of a method that is already defined in
the parent class.

The overridden method in the child class must have the same name and parameters
as the method in the parent class.

When the method is called using an object of the child class, the child class version
is executed instead of the parent class version.

# Parent Class
class Animal:
def sound(self):
print("Animals make sounds")

# Child Class
class Dog(Animal):
# Overriding the parent class method
def sound(self):
print("Dog barks")

# Create object
d = Dog()

# Calls overridden method


[Link]()
Explanation

 Animal has a method sound().


 Dog inherits from Animal and overrides the sound() method.
 When [Link]() is called, Python executes the Dog class version instead of
the Animal class version.

8. Explain polymorphism in Python with a real-world example. How does Python


achieve polymorphism through method overriding?

Polymorphism in Python

Polymorphism means "many forms." In Python, polymorphism allows the same


method name or interface to perform different actions depending on the object that
invokes it.

It enables a single operation to work with objects of different classes, making


programs more flexible and extensible.

Polymorphism Through Method Overriding

Python achieves polymorphism through method overriding, where a child class


provides its own implementation of a method already defined in the parent class.

# Parent Class
class Vehicle:
def start(self):
print("Vehicle is starting")

# Child Class 1
class Car(Vehicle):
def start(self):
print("Car starts with a push button")

# Child Class 2
class Bike(Vehicle):
def start(self):
print("Bike starts with a self-start")

# Child Class 3
class ElectricCar(Vehicle):
def start(self):
print("Electric car powers its motor")

# Polymorphism
vehicles = [Car(), Bike(), ElectricCar()]

for v in vehicles:
[Link]()

9. What is duck typing in Python? How does it relate to polymorphism? Illustrate


with a program.
Duck Typing in Python

Duck Typing is a concept in Python where the type of an object is determined by


its behavior (methods and attributes) rather than its actual class.

The phrase comes from the saying:

"If it looks like a duck, swims like a duck, and quacks like a duck, then it is
probably a duck."

In Python, if an object has the required method or attribute, it can be used


regardless of its class.

Relation to Polymorphism

Duck typing is a form of polymorphism in Python.

 Polymorphism allows different objects to respond to the same method call in


different ways.
 Duck typing focuses on whether an object supports the required behavior,
not whether it belongs to a particular class hierarchy.

Thus, objects of unrelated classes can be used interchangeably as long as they


provide the required methods.

class Duck:
def sound(self):
print("Quack Quack")

class Dog:
def sound(self):
print("Bow Bow")

class Cat:
def sound(self):
print("Meow Meow")

# Function using duck typing


def make_sound(animal):
[Link]()
# Objects of different classes
d = Duck()
dg = Dog()
c = Cat()

make_sound(d)
make_sound(dg)
make_sound(c)

10. What is the difference between overloading and overriding in Python? Explain
both with an example.

Comparison: Overloading vs Overriding


Feature Method Overloading Method Overriding
Same method name with different Redefining a parent class
Definition
parameters method in a child class
Inheritance
No Yes
Required
Number of Classes Usually one class Parent and child classes
Same name and same
Method Signature Same name, different parameters
parameters
Purpose Handle different input arguments Change inherited behavior
Not directly supported (achieved
Python Support Fully supported
using default arguments or *args)
Polymorphism Compile-time concept (in other
Runtime polymorphism
Type languages)

Example
# Overloading-like behavior
class Calculator:
def add(self, a, b, c=0):
return a + b + c

# Overriding
class Animal:
def sound(self):
print("Animal sound")

class Cat(Animal):
def sound(self):
print("Cat meows")

# Testing Overloading
calc = Calculator()
print([Link](5, 10))
print([Link](5, 10, 15))

# Testing Overriding
c = Cat()
[Link]()

11. Define an abstract class in Python. How is it created using the ABC module?
Write a program to demonstrate abstract methods.

Abstract Class in Python

Definition

An Abstract Class is a class that cannot be instantiated directly and is used as a


blueprint for other classes. It may contain one or more abstract methods, which are
methods declared but not implemented in the abstract class.

Any class that inherits from an abstract class must provide implementations for all
its abstract methods.

Python provides the ABC (Abstract Base Class) module to create abstract classes.

Creating an Abstract Class Using ABC

To create an abstract class:

1. Import ABC and abstractmethod from the abc module.


2. Inherit the class from ABC.
3. Decorate abstract methods with @abstractmethod.

Syntax
from abc import ABC, abstractmethod

class Shape(ABC):

@abstractmethod
def area(self):
pass
from abc import ABC, abstractmethod

# Abstract Class
class Shape(ABC):

@abstractmethod
def area(self):
pass

# Derived Class
class Rectangle(Shape):
def __init__(self, length, breadth):
[Link] = length
[Link] = breadth

def area(self):
return [Link] * [Link]

# Derived Class
class Circle(Shape):
def __init__(self, radius):
[Link] = radius

def area(self):
return 3.14 * [Link] * [Link]

# Create objects
r = Rectangle(10, 5)
c = Circle(7)

print("Area of Rectangle =", [Link]())


print("Area of Circle =", [Link]())

12. What are interfaces in Python? How are they simulated using abstract base
classes? Illustrate with an example.

Definition

An interface is a blueprint that specifies a set of methods that a class must


implement. It defines what a class should do, but not how it should do it.

Unlike Java, Python does not have a separate interface keyword. Interfaces are
typically simulated using Abstract Base Classes (ABCs) from the abc module.

Simulating Interfaces Using Abstract Base Classes


In Python:

 An interface is created as an abstract class.


 All methods are declared as abstract methods using @abstractmethod.
 Any class implementing the interface must provide definitions for all
abstract methods.
 Objects cannot be created from the interface itself.

Steps

1. Import ABC and abstractmethod.


2. Create a class inheriting from ABC.
3. Declare abstract methods.
4. Implement those methods in derived classes.

from abc import ABC, abstractmethod

# Interface
class Payment(ABC):

@abstractmethod
def pay(self, amount):
pass

# Implementing Class 1
class CreditCard(Payment):
def pay(self, amount):
print(f"Paid ₹{amount} using Credit Card")

# Implementing Class 2
class UPI(Payment):
def pay(self, amount):
print(f"Paid ₹{amount} using UPI")

# Creating objects
p1 = CreditCard()
p2 = UPI()

[Link](500)
[Link](1000)

13. Explain how the __add__() method is used to overload the '+' operator. Write a
Python program to add two complex numbers using operator overloading.
Operator Overloading Using __add__() in Python

What is Operator Overloading?

Operator Overloading is a feature of Python that allows operators such as +, -, *,


and / to work with user-defined objects.

Python provides special methods (magic methods) to overload operators. For the
addition (+) operator, Python uses the __add__() method.

How __add__() Works

When the + operator is used between two objects:

obj1 + obj2
obj1.__add__(obj2)

Here:

 self refers to obj1


 other refers to obj2

class Complex:
def __init__(self, real, imag):
[Link] = real
[Link] = imag

# Overloading + operator
def __add__(self, other):
real_part = [Link] + [Link]
imag_part = [Link] + [Link]
return Complex(real_part, imag_part)

def display(self):
print(f"{[Link]} + {[Link]}i")

# Create two complex numbers


c1 = Complex(4, 5)
c2 = Complex(3, 2)

# Add complex numbers using +


c3 = c1 + c2

print("First Complex Number:")


[Link]()

print("Second Complex Number:")


[Link]()

print("Sum of Complex Numbers:")


[Link]()

14. What are __getitem__() and __setitem__() methods in Python? Explain their
purpose with a suitable example.

__getitem__() and __setitem__() Methods in Python

__getitem__() and __setitem__() are special (magic) methods that allow objects of
a class to behave like containers such as lists and dictionaries.

 __getitem__() is called when an object is accessed using square brackets [].


 __setitem__() is called when a value is assigned using square brackets [].

1. __getitem__() Method

Purpose

Used to retrieve an item from an object using an index or key.

Syntax
def __getitem__(self, key):
# return value
class MyList:
def __init__(self):
[Link] = [10, 20, 30, 40]

def __getitem__(self, index):


return [Link][index]

obj = MyList()

print(obj[0])
print(obj[2])

2. __setitem__() Method

Purpose

Used to assign or modify a value using an index or key.

Syntax
def __setitem__(self, key, value):
# set value
Example:
class MyList:
def __init__(self):
[Link] = [10, 20, 30, 40]

def __getitem__(self, index):


return [Link][index]

def __setitem__(self, index, value):


[Link][index] = value

obj = MyList()

obj[1] = 100

print(obj[1])
print([Link])

15. Develop a Python program to implement multilevel inheritance with classes


Vehicle → Car → ElectricCar. Demonstrate attribute access at each level.
# Base Class
class Vehicle:
def __init__(self, brand):
[Link] = brand

def show_vehicle(self):
print("Brand:", [Link])

# Derived Class
class Car(Vehicle):
def __init__(self, brand, model):
super().__init__(brand)
[Link] = model

def show_car(self):
print("Model:", [Link])

# Derived Class of Car


class ElectricCar(Car):
def __init__(self, brand, model, battery_capacity):
super().__init__(brand, model)
self.battery_capacity = battery_capacity

def show_electric_car(self):
print("Battery Capacity:", self.battery_capacity, "kWh")

# Create object of ElectricCar


ec = ElectricCar("Tesla", "Model 3", 75)

# Access attributes and methods from all levels


print("Accessing Vehicle Attribute:")
ec.show_vehicle()

print("\nAccessing Car Attribute:")


ec.show_car()

print("\nAccessing ElectricCar Attribute:")


ec.show_electric_car()

print("\nDirect Attribute Access:")


print("Brand =", [Link])
print("Model =", [Link])
print("Battery Capacity =", ec.battery_capacity, "kWh")

16. Design a Python class hierarchy for a university system: Person → Employee →
Professor. Implement constructors using super() and display relevant information.
# Base Class
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

def display_person(self):
print("Name:", [Link])
print("Age:", [Link])

# Derived Class
class Employee(Person):
def __init__(self, name, age, emp_id, salary):
super().__init__(name, age)
self.emp_id = emp_id
[Link] = salary

def display_employee(self):
print("Employee ID:", self.emp_id)
print("Salary:", [Link])

# Derived Class of Employee


class Professor(Employee):
def __init__(self, name, age, emp_id, salary, department):
super().__init__(name, age, emp_id, salary)
[Link] = department

def display_professor(self):
print("Department:", [Link])

# Create object
prof = Professor("Dr. Rajesh", 45, "EMP101", 85000, "Computer Science")

# Display information
print("Professor Details")
print("-----------------")
prof.display_person()
prof.display_employee()
prof.display_professor()

17. Write a Python program to demonstrate all five types of inheritance (single,
multiple, multilevel, hierarchical, hybrid) with appropriate class examples. Show
object creation and method calls for each.

1. Single Inheritance

A child class inherits from one parent class.

print("----- Single Inheritance -----")

class Person:
def show_person(self):
print("I am a Person")

class Student(Person):
def show_student(self):
print("I am a Student")

s = Student()
s.show_person()
s.show_student()

2. Multiple Inheritance

A child class inherits from more than one parent class.

print("\n----- Multiple Inheritance -----")

class Father:
def show_father(self):
print("Father's Property")

class Mother:
def show_mother(self):
print("Mother's Property")

class Child(Father, Mother):


def show_child(self):
print("Child's Property")

c = Child()
c.show_father()
c.show_mother()
c.show_child()

3. Multilevel Inheritance

A class inherits from a derived class.

print("\n----- Multilevel Inheritance -----")

class Vehicle:
def show_vehicle(self):
print("This is a Vehicle")

class Car(Vehicle):
def show_car(self):
print("This is a Car")

class ElectricCar(Car):
def show_electric(self):
print("This is an Electric Car")

e = ElectricCar()

e.show_vehicle()
e.show_car()
e.show_electric()

4. Hierarchical Inheritance

Multiple child classes inherit from the same parent class.

print("\n----- Hierarchical Inheritance -----")


class Animal:
def eat(self):
print("Animal Eats")

class Dog(Animal):
def bark(self):
print("Dog Barks")

class Cat(Animal):
def meow(self):
print("Cat Meows")

d = Dog()
c = Cat()

[Link]()
[Link]()

[Link]()
[Link]()

5. Hybrid Inheritance

Hybrid inheritance is a combination of two or more inheritance types.

print("\n----- Hybrid Inheritance -----")

# Base Class
class Person:
def show_person(self):
print("I am a Person")

# Hierarchical Inheritance
class Employee(Person):
def show_employee(self):
print("I am an Employee")

class Student(Person):
def show_student(self):
print("I am a Student")

# Multiple Inheritance
class TeachingAssistant(Employee, Student):
def show_ta(self):
print("I am a Teaching Assistant")
ta = TeachingAssistant()

ta.show_person()
ta.show_employee()
ta.show_student()
ta.show_ta()

19. Write a Python program to create an Employee class with attributes and
demonstrate hybrid inheritance by combining multiple and multilevel inheritance.
Test with at least 3 derived classes.
# Base Class
class Employee:
def __init__(self, emp_id, name):
self.emp_id = emp_id
[Link] = name

def show_employee(self):
print("Employee ID:", self.emp_id)
print("Employee Name:", [Link])

# Derived Class (Multilevel)


class Manager(Employee):
def __init__(self, emp_id, name, department):
super().__init__(emp_id, name)
[Link] = department

def show_manager(self):
print("Department:", [Link])

# Another Parent Class


class Trainer:
def __init__(self, subject):
[Link] = subject

def show_trainer(self):
print("Training Subject:", [Link])

# Hybrid Inheritance (Multiple + Multilevel)


class TeamLead(Manager, Trainer):
def __init__(self, emp_id, name, department, subject, team_size):
Manager.__init__(self, emp_id, name, department)
Trainer.__init__(self, subject)
self.team_size = team_size

def show_teamlead(self):
print("Team Size:", self.team_size)

# Object Creation
tl = TeamLead("EMP101", "Rahul", "IT", "Python", 12)

print("----- Team Lead Details -----")


tl.show_employee()
tl.show_manager()
tl.show_trainer()
tl.show_teamlead()

[Link] a Python program to demonstrate runtime polymorphism using a list


of different shape objects (Circle, Rectangle, Triangle), each having an area()
method. Call area() using a loop.
# Base Class
class Shape:
def area(self):
pass

# Derived Class - Circle


class Circle(Shape):
def __init__(self, radius):
[Link] = radius

def area(self):
return 3.14 * [Link] * [Link]

# Derived Class - Rectangle


class Rectangle(Shape):
def __init__(self, length, breadth):
[Link] = length
[Link] = breadth

def area(self):
return [Link] * [Link]

# Derived Class - Triangle


class Triangle(Shape):
def __init__(self, base, height):
[Link] = base
[Link] = height

def area(self):
return 0.5 * [Link] * [Link]
# Create objects
shapes = [
Circle(5),
Rectangle(10, 4),
Triangle(8, 6)
]

# Runtime Polymorphism
for shape in shapes:
print("Area =", [Link]())

21. Implement a Python program to simulate a Library system where Book is a base
class and EBook and PrintedBook are derived classes. Override display_info() and
demonstrate polymorphism.
# Base Class
class Book:
def __init__(self, title, author):
[Link] = title
[Link] = author

def display_info(self):
print("Title:", [Link])
print("Author:", [Link])

# Derived Class - EBook


class EBook(Book):
def __init__(self, title, author, file_size):
super().__init__(title, author)
self.file_size = file_size

def display_info(self):
print("E-Book Details")
print("Title:", [Link])
print("Author:", [Link])
print("File Size:", self.file_size, "MB")

# Derived Class - PrintedBook


class PrintedBook(Book):
def __init__(self, title, author, pages):
super().__init__(title, author)
[Link] = pages

def display_info(self):
print("Printed Book Details")
print("Title:", [Link])
print("Author:", [Link])
print("Pages:", [Link])

# Create Objects
book1 = EBook("Python Programming", "John Smith", 12.5)
book2 = PrintedBook("Data Structures", "Alice Brown", 450)

# Polymorphism using a list


library = [book1, book2]

print("Library Information")
print("-------------------")

for book in library:


book.display_info()
print()

22. Implement a Python program using abstract classes to define a Shape base
class with abstract methods area() and perimeter(). Create Circle and
Rectangle as derived classes.
from abc import ABC, abstractmethod

# Abstract Class
class Shape(ABC):

@abstractmethod
def area(self):
pass

@abstractmethod
def perimeter(self):
pass

# Derived Class - Circle


class Circle(Shape):
def __init__(self, radius):
[Link] = radius

def area(self):
return 3.14 * [Link] * [Link]

def perimeter(self):
return 2 * 3.14 * [Link]
# Derived Class - Rectangle
class Rectangle(Shape):
def __init__(self, length, breadth):
[Link] = length
[Link] = breadth

def area(self):
return [Link] * [Link]

def perimeter(self):
return 2 * ([Link] + [Link])

# Create Objects
c = Circle(5)
r = Rectangle(10, 4)

# Display Results
print("Circle")
print("Area =", [Link]())
print("Perimeter =", [Link]())

print("\nRectangle")
print("Area =", [Link]())
print("Perimeter =", [Link]())

23. Develop a Python program that uses an abstract class Animal with abstract
method speak(). Implement Dog, Cat and Cow subclasses. Demonstrate
polymorphism by calling speak() on a list of animals.
from abc import ABC, abstractmethod

# Abstract Class
class Animal(ABC):

@abstractmethod
def speak(self):
pass

# Subclass 1
class Dog(Animal):
def speak(self):
return "Dog says: Bow Bow"

# Subclass 2
class Cat(Animal):
def speak(self):
return "Cat says: Meow Meow"

# Subclass 3
class Cow(Animal):
def speak(self):
return "Cow says: Moo Moo"

# Create objects
animals = [Dog(), Cat(), Cow()]

# Demonstrate Polymorphism
for animal in animals:
print([Link]())

24. Design a Python class Matrix that supports addition and multiplication of
matrices using operator overloading (__add__ and __mul__). Test with 2x2
matrices.

class Matrix:
def __init__(self, data):
[Link] = data

# Overload + operator
def __add__(self, other):
result = []

for i in range(len([Link])):
row = []
for j in range(len([Link][0])):
[Link]([Link][i][j] + [Link][i][j])
[Link](row)

return Matrix(result)

# Overload * operator
def __mul__(self, other):
result = [[0 for j in range(len([Link][0]))]
for i in range(len([Link]))]

for i in range(len([Link])):
for j in range(len([Link][0])):
for k in range(len([Link])):
result[i][j] += [Link][i][k] * [Link][k][j]

return Matrix(result)
def display(self):
for row in [Link]:
print(row)

# Create two 2x2 matrices


A = Matrix([[1, 2],
[3, 4]])

B = Matrix([[5, 6],
[7, 8]])

# Matrix Addition
C=A+B

# Matrix Multiplication
D=A*B

print("Matrix A")
[Link]()

print("\nMatrix B")
[Link]()

print("\nA + B")
[Link]()

print("\nA * B")
[Link]()

25. Write a Python program to create a Book class that supports the 'in' operator to
check if a word appears in the title, and indexing using [] to access characters of the
title.

class Book:
def __init__(self, title):
[Link] = title

# Support 'in' operator


def __contains__(self, word):
return [Link]() in [Link]()

# Support indexing []
def __getitem__(self, index):
return [Link][index]

# Create a Book object


book = Book("Python Programming")

# Using 'in' operator


print("Python" in book)
print("Java" in book)

# Using indexing
print("First character:", book[0])
print("Third character:", book[2])
print("Last character:", book[-1])

26. Develop a Python program implementing __getitem__() and __setitem__()


to create a custom list-like class that supports index-based access and
modification.
class MyList:
def __init__(self):
[Link] = []

# Method for accessing elements


def __getitem__(self, index):
return [Link][index]

# Method for modifying elements


def __setitem__(self, index, value):
[Link][index] = value

# Method to add elements


def append(self, value):
[Link](value)

# Display list
def display(self):
print([Link])

# Create object
lst = MyList()

# Add elements
[Link](10)
[Link](20)
[Link](30)
[Link](40)

print("Original List:")
[Link]()

# Access elements using indexing


print("Element at index 0:", lst[0])
print("Element at index 2:", lst[2])

# Modify elements using indexing


lst[1] = 100
lst[3] = 400

print("\nModified List:")
[Link]()

You might also like