Exercise 41
- Write a Rectangle class in Python language, allowing you to build a rectangle with length and width attributes.
- Create a Perimeter() method to calculate the perimeter of the rectangle and a Area() method to calculate the area of the rectangle.
- Create a method display() that display the length, width, perimeter and area of an object created using an instantiation on rectangle class.
- Create a Parallelepipede child class inheriting from the Rectangle class and with a height attribute and another Volume() method to calculate the volume of the Parallelepiped.
Solution
class Rectangle:
# define constructor with attributes: length and width
def __init__(self, length , width):
self.length = length
self.width = width
# Create Perimeter method
def Perimeter(self):
return 2*(self.length + self.width)
# Create area method
def Area(self):
return self.length*self.width
# create display method
def display(self):
print("The length of rectangle is: ", self.length)
print("The width of rectangle is: ", self.width)
print("The perimeter of rectangle is: ", self.Perimeter())
print("The area of rectangle is: ", self.Area())
class Parallelepipede(Rectangle):
def __init__(self, length, width , height):
Rectangle.__init__(self, length, width)
self.height = height
# define Volume method
def volume(self):
return self.length*self.width*self.height
myRectangle = Rectangle(7 , 5)
myRectangle.display()
print("----------------------------------")
myParallelepipede = Parallelepipede(7 , 5 , 2)
print("the volume of myParallelepipede is: " , myParallelepipede.volume())
The output is:
The length of rectangle is: 7
The width of rectangle is: 5
The perimeter of rectangle is: 24
The area of rectangle is: 35
----------------------------------
the volume of myParallelepipede is: 70
Younes Derfoufi
my-courses.net
my-courses.net
teri meri your mums so hairy
my wood is large