Abstract Base Class in Python

Level 4220 keystrokes

This defines an abstract base class with an abstract method. Subclasses must implement all abstract methods.

Python code

# Import ABC and abstractmethod from abc module
1from abc import ABC, abstractmethod
2
# Define abstract base class inheriting from ABC
3class Shape(ABC):
# @abstractmethod decorator marks method as abstract
4 @abstractmethod
# Abstract method with no implementation
5 def area(self):
# pass is a placeholder: the method has no body
6 pass
7
# Concrete class must implement all abstract methods
8class Circle(Shape):
# Constructor takes the radius r
9 def __init__(self, r):
# Store radius as instance variable
10 self.r = r
# Implement the abstract area method
11 def area(self):
# Calculate and return the circle area (π ≈ 3.14)
12 return 3.14 * self.r ** 2
13
# Create Circle instance with radius 5
14c = Circle(5)
# Print the calculated area
15print(c.area())

Output

78.5
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
  • .× 4
  • *× 3
  • ,× 2
  • =× 2
  • @× 1

More Python examples at level 4

← Python typing practice