Abstract Base Class in Python

Level 5237 keystrokes

This defines an abstract base class Shape that Square must implement. Abstract classes enforce interface contracts in subclasses.

Python code

# Import ABC (Abstract Base Class) and abstractmethod decorator
1from abc import ABC, abstractmethod
2
# Shape inherits from ABC, making it an abstract class
3class Shape(ABC):
# @abstractmethod means subclasses MUST implement this method
4 @abstractmethod
5 def area(self):
# pass is a placeholder - the method has no implementation
6 pass
7
# Square inherits from Shape and must implement area()
8class Square(Shape):
# Constructor stores the side length
9 def __init__(self, side):
10 self.side = side
11
# Concrete implementation of the abstract area() method
12 def area(self):
# Area of square = side²
13 return self.side ** 2
14
# Create a Square with side length 5
15s = Square(5)
# Call area() and print the result
16print(f"Area: {s.area()}")

Output

Area: 25
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
  • :× 6
  • _× 4
  • .× 3
  • ,× 2
  • "× 2
  • *× 2
  • =× 2
  • {× 1

More Python examples at level 5

← Python typing practice