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 ofShape, whose methodarea(self)returnswidth * height; - a class
Circle(radius), a circle and also a child class ofShape, whose methodarea(self)returnsmath.pi * radius ** 2, wheremath.piis the number π; - a function
total_area(shapes)that returns the sum of the areas of all the shapes in the listshapes.
Examples:
Rect(2, 3).area()→6Circle(1).area()→3.141592653589793total_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.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.