Editor

Build a Shape Area Calculator

Intermediate · Write the code · from Python Inheritance: Subclasses, Polymorphism, and super()

From the lesson: Python Inheritance: Subclasses, Polymorphism, and super()

Think about how scientists classify animals. A Dog is a type of Mammal, which is a type of Animal. Each level inherits traits from the one above it: all animals breathe, all mammals are warm-blooded, and all dogs bark.

Read the lesson

Create a Shape base class with a method area() that returns 0. Then create two subclasses:

  • Square with a side attribute - area() returns side * side
  • Triangle with base and height - area() returns 0.5 * base * height
  • Create a list with a Square(4) and a Triangle(6, 3). Loop through the list and print each area.

    # Build your Shape hierarchy here

    More Inheritance exercises

    All Python exercises · 50 practice problems · Object-Oriented Programming quiz