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 decorator1from abc import ABC, abstractmethod2 # Shape is abstract: Shape() itself cannot be instantiated3class Shape(ABC): # Every concrete subclass must implement area4 @abstractmethod5 def area(self): # No implementation in the base class6 pass7 # Square is a concrete subclass of Shape8class Square(Shape): # The constructor receives the side length9 def __init__(self, side): # Store it on the instance10 self.side = side11 # Implement the required area method12 def area(self): # Area of a square: side squared13 return self.side ** 214 # Create Square(4) and print its area: 4 ** 2 = 1615print(Square(4).area())Output
16
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