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 module1from abc import ABC, abstractmethod2 # Define abstract base class inheriting from ABC3class Shape(ABC): # @abstractmethod decorator marks method as abstract4 @abstractmethod # Abstract method with no implementation5 def area(self): # pass is a placeholder: the method has no body6 pass7 # Concrete class must implement all abstract methods8class Circle(Shape): # Constructor takes the radius r9 def __init__(self, r): # Store radius as instance variable10 self.r = r # Implement the abstract area method11 def area(self): # Calculate and return the circle area (π ≈ 3.14)12 return 3.14 * self.r ** 213 # Create Circle instance with radius 514c = Circle(5)# Print the calculated area15print(c.area())Output
78.5
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