Abstract Classes & ABC
An abstract class defines an interface that subclasses must implement. Python's abc module provides the tools to enforce this.
Defining an Abstract Class
from abc import ABC, abstractmethod
class Shape(ABC):
"""Abstract base class for shapes."""
@abstractmethod
def area(self) -> float:
"""Return the area of the shape."""
...
@abstractmethod
def perimeter(self) -> float:
"""Return the perimeter of the shape."""
...
def describe(self):
# Concrete method — shared implementation
return f"{type(self).__name__}: area={self.area():.2f}"Concrete Subclasses
import math
class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): return math.pi * self.r ** 2
def perimeter(self): return 2 * math.pi * self.r
class Square(Shape):
def __init__(self, s): self.s = s
def area(self): return self.s ** 2
def perimeter(self): return 4 * self.s
# Shape() # TypeError: Can't instantiate abstract class
c = Circle(5)
print(c.describe()) # Circle: area=78.54abstractproperty (Modern)
class Vehicle(ABC):
@property
@abstractmethod
def fuel_type(self) -> str: ...
class ElectricCar(Vehicle):
@property
def fuel_type(self): return "electric"