Advanced OOP and patterns · 8 / 15 Exercise Medium

Shapes with an abstract class

Objective

An abstract class (abc.ABC with @abstractmethod) defines a contract: it forces subclasses to implement certain methods and cannot be instantiated directly. Each shape computes its area in its own way, and the code using them does not need to know which is which (polymorphism).

Instructions

  • Define the abstract class Shape with the abstract method area() and the subclasses Circle (radius), Square (side) and Triangle (base and height).
  • The program tries to create Shape() and, when it fails with TypeError, shows Cannot instantiate Shape. Then it reads n and n lines kind measures (for example circle 2 or triangle 3 4); show Name: area per line and at the end Total: x (2 decimals).
Input
2
circle 1
square 2
Output
Cannot instantiate Shape
Circle: 3.14
Square: 4.00
Total: 7.14

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise