Syntax
from abc import ABC, abstractmethodExamples
Basic Abstract Class
Defining a base class that cannot be instantiated on its own.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
# shape = Shape() # would raise TypeError - can't instantiate an abstract classEnforcing Implementation in Subclasses
Every subclass must implement the abstract method or it cannot be instantiated either.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
shapes = [Circle(5), Square(4)]
for shape in shapes:
print(f"{type(shape).__name__}: {shape.area():.2f}")Abstract Class with Concrete Methods
Abstract classes can also include regular, already-implemented methods that subclasses inherit as-is.
from abc import ABC, abstractmethod
class Employee(ABC):
def __init__(self, name):
self.name = name
@abstractmethod
def calculate_pay(self):
pass
def display(self): # concrete method, shared by all subclasses
print(f"{self.name}: ${self.calculate_pay():.2f}")
class SalariedEmployee(Employee):
def __init__(self, name, salary):
super().__init__(name)
self.salary = salary
def calculate_pay(self):
return self.salary / 12
emp = SalariedEmployee("John", 48000)
emp.display() # John: $4000.00Best practices
- Use abstract base classes to guarantee that every subclass implements a required set of methods, catching missing implementations early
- Combine abstract methods with regular concrete methods on the same base class for shared functionality plus enforced customization points
- Remember you cannot instantiate a class that still has unimplemented abstract methods - Python raises a TypeError immediately
- Reach for ABCs when designing a plugin-style system or a family of related classes that must all support the same interface
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference