Inheritance and Polymorphism
Problem Statement
Implement a class hierarchy for shapes.
Background
Inheritance allows classes to share behavior:
class Child(Parent):
def __init__(self):
super().__init__()
Your Task
Create an inheritance hierarchy:
-
Base class Shape with:
- name attribute
- area() method (returns 0)
- str returning "{name}: area={area}"
-
Rectangle(Shape) with:
- Constructor taking width and height
- area() returning width * height
-
Circle(Shape) with:
- Constructor taking radius
- area() returning π * radius²
Example
Rectangle(4, 5)
Rectangle: area=20
- Input:
Rectangle(4, 5)builds a rectangle withwidthandheight. The caller never passes a name, yet the printed text starts withRectangle, so each kind of shape must supply its own label to the sharedShapepart. - Math: a rectangle's area is width times height: . Both sides are whole numbers, so the area stays the integer , and rounding it to 2 decimal places leaves it as (not or ).
- Output: the text has the form "name: area=value", giving
Rectangle: area=20. That format belongs to the baseShape; it works for every shape because it asks the object for its own area, and the rectangle's version is the one that answers. - Compare a circle: one of radius has area , which rounds to , so it prints
Circle: area=28.27. - Notice: a plain
Shapewith no override reports an area of ; only the subclasses know a real formula.
Constraints
- Use math.pi for π
- Round area to 2 decimal places in str