Start learning free

LESSON 642 OF 673 · OBJECT-ORIENTED PROGRAMMING

Shape Area in Python: Abstract Classes with ABC

Practice Read the full explanation

You write an abstract class and the areas of three shapes.

Shape is abstract. It has two abstract methods:

  • area() returns the shape's area.
  • name() returns the shape's name.

It also has one concrete method, describe(). It returns a text such as Square with area 25. That is the name, then with area, then the area.

Three shapes inherit from Shape:

  • Rectangle(width, height) has area width × height.
  • Square(side) has area side × side.
  • RightTriangle(a, b) has sides a and b that meet at a right angle. Its area is a × b / 2, rounded down.

Their constructors and name() methods are already written. You write each area().

In Python, Shape inherits from ABC. Each abstract method gets @abstractmethod and the body pass.

For each shape, the harness prints describe() on its own line.

 

Example 1:

Input: Rectangle(3, 4), Square(5), RightTriangle(3, 4)
Output:
Rectangle with area 12
Square with area 25
Right triangle with area 6

Explanation: 3 × 4 = 12 and 5 × 5 = 25.
The triangle is half of 3 × 4, so 6.

Example 2:

Input: RightTriangle(3, 5), Square(1)
Output:
Right triangle with area 7
Square with area 1

Explanation: Half of 3 × 5 is 7.5.
It rounds down to 7.

Example 3:

Input: Rectangle(1, 7), RightTriangle(1, 1)
Output:
Rectangle with area 7
Right triangle with area 0

Explanation: A 1 by 7 rectangle has area 7.
Half of 1 × 1 rounds down to 0.

 

Constraints:

  • 1 to 100 shapes.
  • Each size is a whole number from 1 to 10,000.
STEP 1 OF 6
    Ctrl + Enter to check

    PYTHON · OBJECT-ORIENTED PROGRAMMING

    Shape Area in Python, explained

    Problem overview

    You write an abstract class Shape and the areas of three shapes. Shape has two abstract methods, area() and name(), and one concrete method, describe(), which returns text such as Square with area 25: the name, then with area, then the area.

    Three classes inherit from it. Their constructors and name() methods are given; you write each area():

    • Rectangle(width, height): width times height;
    • Square(side): side times side;
    • RightTriangle(a, b): the two sides meeting at the right angle, area a * b / 2 rounded down.

    For Rectangle(3, 4), Square(5) and RightTriangle(3, 4) the tests print Rectangle with area 12, Square with area 25 and Right triangle with area 6.

    Approach

    An abstract class is a template: it says what every shape must be able to do (area and name) without saying how. It can also hold code that is the same for all shapes. describe() is that code. It calls self.name() and self.area() without knowing which shape it runs on, and each shape's own methods fill in the text. So describe is written once and works for every shape, including ones added later.

    In Python, you make a class abstract by inheriting from ABC (from the abc module) and marking each abstract method with @abstractmethod. The body is just pass.

    Step by step

    1. Abstract area: put @abstractmethod above def area(self) in Shape, with the body pass.
    2. Abstract name the same way.
    3. Write describe: return self.name(), then " with area ", then str(self.area()). The area is a number, and str turns it into text so that + can join it.
    4. Rectangle's area: self._width * self._height.
    5. Square's area: self._side * self._side.
    6. Triangle's area: self._a * self._b // 2. A right triangle is half of an a by b rectangle, and // drops the fraction.

    The solution in Python

    from abc import ABC, abstractmethod
    
    class Shape(ABC):
        @abstractmethod
        def area(self): pass
    
        @abstractmethod
        def name(self): pass
    
        def describe(self):
            return self.name() + " with area " + str(self.area())
    
    class Rectangle(Shape):
        def __init__(self, width, height):
            self._width = width
            self._height = height
    
        def name(self):
            return "Rectangle"
    
        def area(self):
            return self._width * self._height
    
    class Square(Shape):
        def __init__(self, side):
            self._side = side
    
        def name(self):
            return "Square"
    
        def area(self):
            return self._side * self._side
    
    class RightTriangle(Shape):
        def __init__(self, a, b):
            self._a = a
            self._b = b
    
        def name(self):
            return "Right triangle"
    
        def area(self):
            return self._a * self._b // 2
    

    Running the three examples:

    for shape in [Rectangle(3, 4), Square(5), RightTriangle(3, 4),
                  RightTriangle(3, 5), Rectangle(1, 7), RightTriangle(1, 1)]:
        print(shape.describe())
    
    Rectangle with area 12
    Square with area 25
    Right triangle with area 6
    Right triangle with area 7
    Rectangle with area 7
    Right triangle with area 0
    

    Adding a shape later

    The benefit of the abstract class shows when a new shape appears. In a file of your own, a parallelogram needs only a constructor, a name and an area. It inherits describe unchanged:

    class Parallelogram(Shape):
        def __init__(self, base, height):
            self._base = base
            self._height = height
    
        def name(self):
            return "Parallelogram"
    
        def area(self):
            return self._base * self._height
    
    shapes = [Square(2), Parallelogram(6, 4)]
    for shape in shapes:
        print(shape.describe())
    print(sum(s.area() for s in shapes))
    
    Square with area 4
    Parallelogram with area 24
    28
    

    Nothing in Shape changed. Any code that holds a list of shapes, like the loop above, handles the new class as soon as it exists, because it only calls area() and describe(). This is the same idea as a loop that calls one method on mixed objects: the caller depends on the promise in Shape, not on the individual classes.

    Python details

    • Floor division. 3 * 5 / 2 is 7.5, but 3 * 5 // 2 is 7, and 1 * 1 // 2 is 0. With /, describe() would print Right triangle with area 7.5. Since the sides are positive, flooring and "rounding down" agree.
    • The class can't be created. Shape() raises TypeError: Can't instantiate abstract class Shape without an implementation for abstract methods 'area', 'name'.
    • A child must fill in every abstract method. A Circle(Shape) that defines only name can't be created either: the error names area as missing. That is why each shape in the starter code already has a name.
    • Precedence. self._a * self._b // 2 multiplies first, then divides, because * and // have the same precedence and group from the left.
    • The abstract body. def area(self): pass on one line is valid; the body never runs, since the children replace it.

    How one call to describe runs

    Take RightTriangle(3, 5).describe(). Python finds describe in Shape, because the triangle class doesn't define its own. Inside it, self is the triangle, so self.name() runs the triangle's name and gives "Right triangle". Then self.area() runs the triangle's area: 3 times 5 is 15, and 15 // 2 is 7. The text is "Right triangle", " with area " and "7" joined together. For a square the same line of code produces a different text, because self is a different object.

    This is why the abstract methods exist. describe calls self.area(), so every shape must have one, and Python checks that when you create the object rather than when the call finally fails in the middle of a program.

    Edge cases and common mistakes

    • Using / instead of // gives a float, and for odd products the text shows .5.
    • Forgetting str() in describe raises a TypeError, because Python won't join text and a number with +.
    • Forgetting ABC as the parent. Then @abstractmethod is accepted but not enforced, and nothing stops you from creating a plain shape.
    • Writing describe in each shape. It works, but the point is to write it once in Shape.
    • Forgetting the calls' parentheses in describe: self.name without () is a method object, not the text.
    • A triangle of 1 by 1 has area 0 here, not 1, which is what the third example shows.

    Testing

    These inputs are worth trying, with the text describe() returns for each:

    • Rectangle(1, 1) gives Rectangle with area 1.
    • RightTriangle(9999, 1) gives Right triangle with area 4999: 9999 is odd, so half of it rounds down.
    • RightTriangle(10000, 10000) gives Right triangle with area 50000000.
    • Square(10000) gives Square with area 100000000. Python integers don't overflow, so the largest sizes need no special care.

    The area is always a whole number: only the triangle divides, and // keeps its result an integer.

    One more difference from an interface: Shape is not only a promise, because it also carries working code, describe. That mix of promised methods and shared code is what an abstract class is for. When a class has only promises, it is usually called an interface.

    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free