Abstract Base Classes
PY · Classes & OOPsyntax
from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def method(self): ...example
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float: ...
class Circle(Shape):
def __init__(self, radius: float):
self.radius = radius
def area(self) -> float:
return 3.14159 * self.radius ** 2
# shape = Shape() # TypeError: can't instantiate abstract class
circle = Circle(5)
print(f"Area: {circle.area():.2f}")output
Area: 78.54Note Abstract classes cannot be instantiated directly. Subclasses must implement all @abstractmethod methods or they will also be abstract.