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 decorator1from abc import ABC, abstractmethod2 # Shape inherits from ABC, making it an abstract class3class Shape(ABC): # @abstractmethod means subclasses MUST implement this method4 @abstractmethod5 def area(self): # pass is a placeholder - the method has no implementation6 pass7 # Square inherits from Shape and must implement area()8class Square(Shape): # Constructor stores the side length9 def __init__(self, side):10 self.side = side11 # Concrete implementation of the abstract area() method12 def area(self): # Area of square = side²13 return self.side ** 214 # Create a Square with side length 515s = Square(5)# Call area() and print the result16print(f"Area: {s.area()}")Output
Area: 25
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