In: Computer Science
Exercise 1. Rectangle, Circle and Square Write three Python
classes named Rectangle constructed by a length and width, a Circle
constructed by a radius and a Square constructed by a side length.
Both classes should have the methods that compute: - The area - The
diagonal - The perimeter Use as much abstraction as you can. At the
end of the file, use those classes to calculate the perimeter of a
circle with radius the half of the diagonal of a rectangle with
length 20 and width 10.
CODE:
from math import sqrt
#the circle class
class Circle():
def __init__(self, radius):
self.radius = radius
#the area function
def area(self):
return self.radius**2 *3.14
#the perimeter function
def perimeter(self):
return 2*self.radius *3.14
#the rectangle class
class Rectangle():
def __init__(self, length, width):
self.length = length
self.width = width
#the area function
def area(self):
return self.length*self.width
#the perimeter function
def perimeter(self):
return 2*self.length* self.width
#the diagonal function
def diagonal(self):
diagonal = float(sqrt(self.length**2 + self.width**2))
return diagonal
#the square class
class Square():
def __init__(self, length):
self.length = length
#the area function
def area(self):
return self.length * self.length
#the perimeter function
def perimeter(self):
return 4*self.length
#the diagonal function
def diagonal(self):
diagonal = 1.414 * self.length
##new rectangle object with required length and width
NewRectangle = Rectangle(20, 10)
#calculating the diagonal of the rectangle
NewRectangleDiagonal = NewRectangle.diagonal()
#instantiating the circle class with half the diagonal as the
radius
NewCircle = Circle(NewRectangleDiagonal/2)
#print the perimeter of the circle
print(NewCircle.perimeter())
SCREENSHOT:
OUTPUT: