Abstract Base Class in Python

Level 5478 keystrokes

This demonstrates abstract base classes with ABC and @abstractmethod to enforce interface implementation.

Python code

# Import ABC and the abstractmethod decorator
1from abc import ABC, abstractmethod
2
# Shape inherits ABC, so it can't be instantiated while methods stay abstract
3class Shape(ABC):
# @abstractmethod decorator marks method as required
4 @abstractmethod
# area() returns a float; only the signature is defined here
5 def area(self) -> float:
# pass is placeholder - subclasses must implement
6 pass
7
# Another abstract method for perimeter
8 @abstractmethod
# Subclasses must implement perimeter method
9 def perimeter(self) -> float:
# Abstract methods have no implementation
10 pass
11
# Rectangle is a concrete subclass of Shape
12class Rectangle(Shape):
# __init__ initializes width and height
13 def __init__(self, width: float, height: float):
# Store width as instance attribute
14 self.width = width
# Store height as instance attribute
15 self.height = height
16
# Concrete implementation of area method
17 def area(self) -> float:
# Return width times height
18 return self.width * self.height
19
# Concrete implementation of perimeter method
20 def perimeter(self) -> float:
# Return 2 times sum of width and height
21 return 2 * (self.width + self.height)
22
# Create Rectangle instance with width 5, height 3
23rect = Rectangle(5, 3)
# Print area (5*3 = 15) and perimeter (2*(5+3) = 16)
24print(f"Area: {rect.area()}, Perimeter: {rect.perimeter()}")

Output

Area: 15, Perimeter: 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.

  • (× 12
  • )× 12
  • :× 11
  • .× 8
  • ,× 5
  • _× 4
  • -× 4
  • >× 4
  • =× 3
  • "× 2

More Python examples at level 5

← Python typing practice