Shapes and Inheritance
Write these classes:
Shape: a methodarea()that raisesNotImplementedError, and a methoddescribe()that returns text like"Rectangle with area 12.00"(the class name, then the area with 2 decimals).Rectangle(width, height): a subclass witharea().Circle(radius): a subclass witharea()(usemath.pi).Square(side): a subclass ofRectangle.
describe() must be written once, in Shape, and work for every subclass.
Understand the problem
Revise the ideas behind class hierarchies.
What is polymorphism?
- Using many different variable names
- Calling the same method on different objects and each object does the right thing for its own class
- 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"?
- It cannot; each subclass must override it
type(self).__name__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.)
VISIBLE = 3
CASES = [
('result = Rectangle(3, 4).area()', 12, 'a rectangle'),
('import math\nresult = math.isclose(Circle(1).area(), math.pi)', True, 'a circle'),
('result = Square(3).area()', 9, 'a square'),
('result = Rectangle(3, 4).describe()', 'Rectangle with area 12.00', 'a description'),
('result = Circle(2).describe()', 'Circle with area 12.57', 'a circle description'),
('result = Square(2).describe()', 'Square with area 4.00', 'the class name of the subclass'),
('result = error_of(Shape().area)', 'NotImplementedError', 'the base class has no area'),
('result = (isinstance(Square(2), Rectangle), isinstance(Square(2), Shape), isinstance(Circle(1), Rectangle))', (True, True, False), 'the class relations'),
('result = sum(s.area() for s in [Rectangle(1, 2), Square(2)])', 6, 'a mixed list'),
]