Deviopath › Python

Shapes with Inheritance and super()

Medium · Classes

A subclass inherits the methods of its parent class and can override some of them. Inside the subclass, super().__init__(...) runs the parent constructor, so shared setup lives in one place.

Shape is already written: it stores a name, and describe() uses self.area(), rounded to 2 decimals. Write two subclasses:

- Rectangle(width, height): calls super().__init__("Rectangle"), and area() returns width * height. - Circle(radius): calls super().__init__("Circle"), and area() returns math.pi * radius ** 2.

The driver describe_shapes is already written: it builds the shapes and returns their descriptions.

Next: Fibonacci Generator