Medium: Interview Core · Problem 49 of 82

Shapes and Inheritance

MediumClassesPython

Write these classes:

  • Shape: a method area() that raises NotImplementedError, and a method describe() that returns text like "Rectangle with area 12.00" (the class name, then the area with 2 decimals).
  • Rectangle(width, height): a subclass with area().
  • Circle(radius): a subclass with area() (use math.pi).
  • Square(side): a subclass of Rectangle.

describe() must be written once, in Shape, and work for every subclass.

Understand the problem

Revise the ideas behind class hierarchies.

What is polymorphism?

  1. Using many different variable names
  2. Calling the same method on different objects and each object does the right thing for its own class
  3. Copying code between classes

Code such as for shape in shapes: shape.area() does not need to know the exact class. Each class provides its own area, and Python picks the right one. This is what makes a base class useful.

How can describe() in the base class show the subclass name, such as "Circle"?

  1. It cannot; each subclass must override it
  2. type(self).__name__
  3. Shape.__name__

type(self) is the class of the actual object, so type(self).__name__ gives "Circle" for a circle. Shape.__name__ would always say "Shape".

Write the solution

Write all four classes.

class Shape:
    # Write your code here.
    pass
Hint 1: a question to ask yourself

What belongs in the base class because every shape shares it, and what must each subclass provide on its own?

Hint 2: the shape of the answer

Shape.area raises NotImplementedError. Shape.describe calls self.area(). Rectangle and Circle store their sizes and override area. Square.__init__ calls super().__init__(side, side).

Reflect

Solution

import math

class Shape:
    def area(self):
        raise NotImplementedError("subclasses must implement area()")

    def describe(self):
        return f"{type(self).__name__} with area {self.area():.2f}"


class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height


class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * self.radius ** 2


class Square(Rectangle):
    def __init__(self, side):
        super().__init__(side, side)

What this tests: inheritance, overriding, super(), polymorphism, NotImplementedError, type(self).__name__ and isinstance relations.

The template method pattern: describe() in the base class uses self.area(), which each subclass fills in. The shared logic is written once, and new shapes work without changing it.

Square is a Rectangle: it adds no new method, only a different constructor. isinstance(Square(2), Rectangle) is true. (There is an old debate whether a square really is a rectangle when the objects can be changed; a read-only design avoids it.)

NotImplementedError versus ABC: the simple version fails only when area() is called. An abstract base class (class Shape(ABC) with @abstractmethod on area) refuses to create the base object at all: a stronger check, with a bit more ceremony.

What an interviewer might ask next: Write total_area(shapes) that works for any list of shapes, and explain why adding Triangle needs no change to it. (Polymorphism.)