Abstract Base Class in Python

Level 4220 keystrokes

This uses the abc module to create an abstract base class that defines required methods for subclasses.

Python code

# Import ABC and the abstractmethod decorator
1from abc import ABC, abstractmethod
2
# Shape is abstract: Shape() itself cannot be instantiated
3class Shape(ABC):
# Every concrete subclass must implement area
4 @abstractmethod
5 def area(self):
# No implementation in the base class
6 pass
7
# Square is a concrete subclass of Shape
8class Square(Shape):
# The constructor receives the side length
9 def __init__(self, side):
# Store it on the instance
10 self.side = side
11
# Implement the required area method
12 def area(self):
# Area of a square: side squared
13 return self.side ** 2
14
# Create Square(4) and print its area: 4 ** 2 = 16
15print(Square(4).area())

Output

16
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • (× 8
  • )× 8
  • :× 5
  • _× 4
  • .× 3
  • ,× 2
  • *× 2
  • @× 1
  • =× 1

More Python examples at level 4

← Python typing practice