Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Create a Common Interface for Different Subclasses

Design a Shape interface with multiple subclasses and compute total area polymorphically.

Python practice16 minInheritance & PolymorphismIntermediateLast updated April 8, 2026

Problem statement

Define an abstract base class Shape with an area() method. Implement three subclasses: Rectangle(width, height), Circle(radius), and Triangle(base, height). Each subclass should implement area() to return the numeric area. Then implement total_area(shapes) which accepts a list of Shape instances (or objects implementing area()) and returns the sum of their areas rounded to 6 decimal places (as a float). If the list is empty, return 0.0. Use math.pi for circle area. total_area should not rely on concrete types — it should call area() on each object (demonstrating polymorphism).

Task

Implement subclasses that conform to a common interface and write a function that operates on a list of heterogeneous objects via that interface.

Examples

Rectangle area

Input

Rectangle(3, 4).area()

Output

12.0

Area of a 3x4 rectangle is 12. total_area should return floats (rounded to 6 decimals).

Input format

The grader will call total_area([...]) with a list of shape instances.

Output format

Return a float equal to the sum of areas rounded to 6 decimal places. The string representation (str) will be compared to the expected output.

Constraints

- Use math.pi for circle calculations. - total_area must call area() on each element and return round(sum, 6). - Do not use any external libraries beyond the Python standard library.

Samples

Sample 1

Input

total_area([Rectangle(3,4), Circle(1)])

Output

15.141593

Rectangle area 12 + circle area pi ≈ 3.141592653589793 => sum ≈ 15.141592653589793 rounded to 6 decimals => 15.141593