Shapes and Polymorphism
Completed
Create a base class Shape with area() and name, and subclasses Circle(r), Square(s), Triangle(b, h). Read shapes like circle 2 and print name: area with 2 decimals (use π = math.pi).
Input
Line 1: n. Then n shape lines.
Output
n lines.
Example
Input
3 circle 1 square 3 triangle 4 5
Output
circle: 3.14 square: 9.00 triangle: 10.00
Editor
Python
Hints
Each subclass overrides area().
A dict can map a word to a class.
Solution explanation
Polymorphism: the loop calls area() without caring which shape it has.
Show solution
import math
class Shape:
name = "shape"
def area(self):
raise NotImplementedError
class Circle(Shape):
name = "circle"
def __init__(self, r):
self.r = r
def area(self):
return math.pi * self.r ** 2
class Square(Shape):
name = "square"
def __init__(self, s):
self.s = s
def area(self):
return self.s ** 2
class Triangle(Shape):
name = "triangle"
def __init__(self, b, h):
self.b = b
self.h = h
def area(self):
return self.b * self.h / 2
kinds = {"circle": Circle, "square": Square, "triangle": Triangle}
for _ in range(int(input())):
kind, *nums = input().split()
shape = kinds[kind](*map(float, nums))
print(f"{shape.name}: {shape.area():.2f}")