Assignment Six
Python Programming
Question 1: Basic Class Creation Create a Python class named Book that has three
attributes: title, author, and pages. Write an __init__ method to initialize these attributes
and a __str__ method to return a string in the following format: "Title by Author with Pages
pages". Demonstrate the usage of this class by creating an instance of Book and printing
it.
Question 2: Inheritance and Method Overriding Extend the Book class by creating a
subclass named EBook. The EBook class should have an additional attribute called file_size
(in MB). Override the __str__ method to include the file size in the format: "Title by Author
with Pages pages (FileSize MB)" . Demonstrate the usage of this subclass by creating an
instance of EBook and printing it.
Question 3: Encapsulation Create a class named Rectangle that represents a rectangle.
This class should have private attributes for its width and height. Implement a method
set_dimensions that takes width and height as parameters and sets the dimensions if they
are positive numbers; otherwise, it should not change the dimensions. Also, implement a
method area that returns the area of the rectangle. Demonstrate the usage of this class
by creating an instance, setting its dimensions, and printing its area.
Question 4: Polymorphism Create a Python class named Shape with a method area that
returns 0. Create two subclasses, Circle and Square, that override the area method to
calculate and return the area of the shape (Area of a circle: πr², Area of a square: side²).
Create a function print_area that takes a shape instance and prints the area of the shape
passed to it. Demonstrate polymorphism by passing instances of Circle and Square to the
print_area function.
Submission
Submit a .py file containing the solutions to all four questions. Ensure your code is
executable and free from errors. Include a brief comment at the top of the file with your
name and the submission date.