Skip to content
Exercise · Classes · lesson 11 of 11

Exercise: shape areas

The stub already has the class Shape, a shape with no __init__ of its own whose method area(self) returns 0; do not change it. The math module is already imported in the stub too. Write:

  • a class Rect(width, height), a rectangle and a child class of Shape, whose method area(self) returns width * height;
  • a class Circle(radius), a circle and also a child class of Shape, whose method area(self) returns math.pi * radius ** 2, where math.pi is the number π;
  • a function total_area(shapes) that returns the sum of the areas of all the shapes in the list shapes.

Examples:

  • Rect(2, 3).area() → 6
  • Circle(1).area() → 3.141592653589793
  • total_area([Rect(2, 3), Circle(1)]) → 9.141592653589793

Constraints: sizes are positive numbers; the list may hold instances of Shape, Rect and Circle; for an empty list, total_area returns 0.

Do not add extra imports unless the task says so explicitly.

shapes.py — python
python · 27 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way