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 decorator1from abc import ABC, abstractmethod2 # Shape inherits ABC, so it can't be instantiated while methods stay abstract3class Shape(ABC): # @abstractmethod decorator marks method as required4 @abstractmethod # area() returns a float; only the signature is defined here5 def area(self) -> float: # pass is placeholder - subclasses must implement6 pass7 # Another abstract method for perimeter8 @abstractmethod # Subclasses must implement perimeter method9 def perimeter(self) -> float: # Abstract methods have no implementation10 pass11 # Rectangle is a concrete subclass of Shape12class Rectangle(Shape): # __init__ initializes width and height13 def __init__(self, width: float, height: float): # Store width as instance attribute14 self.width = width # Store height as instance attribute15 self.height = height16 # Concrete implementation of area method17 def area(self) -> float: # Return width times height18 return self.width * self.height19 # Concrete implementation of perimeter method20 def perimeter(self) -> float: # Return 2 times sum of width and height21 return 2 * (self.width + self.height)22 # Create Rectangle instance with width 5, height 323rect = 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. 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