v9.1.1
Menu

Inheritance and Polymorphism

mediumFREEClasses & ObjectsPython OOPPython Foundations

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:

  1. Base class Shape with:

    • name attribute
    • area() method (returns 0)
    • str returning "{name}: area={area}"
  2. Rectangle(Shape) with:

    • Constructor taking width and height
    • area() returning width * height
  3. Circle(Shape) with:

    • Constructor taking radius
    • area() returning π * radius²

Example

Input
Rectangle(4, 5)
Output
Rectangle: area=20
Reasoning
  • Input: Rectangle(4, 5) builds a rectangle with width =4= 4 and height =5= 5. The caller never passes a name, yet the printed text starts with Rectangle, so each kind of shape must supply its own label to the shared Shape part.
  • Math: a rectangle's area is width times height: 4×5=204 \times 5 = 20. Both sides are whole numbers, so the area stays the integer 2020, and rounding it to 2 decimal places leaves it as 2020 (not 20.0020.00 or 20.020.0).
  • Output: the text has the form "name: area=value", giving Rectangle: area=20. That format belongs to the base Shape; 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 33 has area πr2=9π≈28.2743\pi r^2 = 9\pi \approx 28.2743, which rounds to 28.2728.27, so it prints Circle: area=28.27.
  • Notice: a plain Shape with no override reports an area of 00; only the subclasses know a real formula.

Constraints

  • Use math.pi for π
  • Round area to 2 decimal places in str

Learn this in

More from Python Foundations

solution.py

Test results

Sign in to run your code against the test cases.