Below is a program that creates the three classes – Cube (actually a Cuboid), Circle, and Square.
Python
class Shape:
def __init__(self, name):
self.name = name
def findArea(self):
raise NotImplementedError("Subclass must implement the findArea method")
def display(self):
print("Shape:", self.name)
class Cube(Shape):
def __init__(self, name, length, width, height):
super().__init__(name)
self.length = length
self.width = width
self.height = height
def findArea(self):
surfaceArea = 2 * ((self.length * self.width) + (self.length * self.height) + (self.width * self.height))
return surfaceArea
def display(self):
super().display()
print("Area:", self.findArea())
class Circle(Shape):
def __init__(self, name, radius):
super().__init__(name)
self.radius = radius
def findArea(self):
area = 3.14 * self.radius * self.radius
return area
def display(self):
super().display()
print("Area:", self.findArea())
class Square(Shape):
def __init__(self, name, side):
super().__init__(name)
self.side = side
def findArea(self):
area = self.side * self.side
return area
def display(self):
super().display()
print("Area:", self.findArea())
def generateShapes():
shapes = []
for i in range(10):
randomNumber = random.randint(0, 2)
if randomNumber == 0:
newShape = Circle("Circle", 4.3)
elif randomNumber == 1:
newShape = Square("Square", 4.0)
else:
newShape = Cube("Cube", 4.0, 4.0, 4.0)
shapes.append(newShape)
return shapes
def printResults(option):
if option == 1:
fileName = input("Enter name of file to save your result: ")
with open(fileName, 'w') as f:
for shape in shapes:
shape.display()
f.write(shape.name + " " + str(shape.findArea()) + "\\")
elif option == 2:
for shape in shapes:
shape.display()
elif option == 3:
print("Shape\tArea\\")
for shape in shapes:
shape.display()
if __name__ == "__main__":
while True:
print("welcome to my shape generator!")
print("Please select which option to run the program:")
print("1. Save the results into a file. The program will ask you to input a file name.")
print("2. Print the results on screen.")
print("3. Print the results inside GUI Windows")
print("4. Exit")
choice = int(input("Enter: "))
if choice == 1:
printResults(1)
elif choice == 2:
printResults(2)
elif choice == 3:
printResults(3)
else:
break
So, the above program prompts the user to select one of four options:
- Save the results into a file. The program will ask the user to input a filename.
- Print the results on screen.
- Print the results inside GUI Windows
- Quit the program
So, Based on the user's choice, the program creates a list of ten objects of the given shapes (Circle, Square, and Cube) using a random number generator, and then prints the results to the file, screen, or GUI window, depending on the user's choice.