Skip to main content

Python Abstract Class

Python allows to define Abstract Classes thanks to the use of abc (abstract base class) module.

Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes cannot be instantiated, and require subclasses to provide implementations for the abstract methods.

What is an Abstract Class in Python?

In Python, Abstract Classes serve as blueprints for other classes:

  • Abstract Classes can not be instantiated directly and are meant to be inherited by other classes.
  • Abstract methods within these classes do not contain an implementation and must be implemented by any concrete subclass.

When should you use Abstract Classes?

Abstract classes are typically used in scenarios where you want to provide a common interface for subclasses, and, at the same time, be sure that some methods have specific implementations in those subclasses.

Define an Abstract Class in Python

The abc module provides you with the infrastructure for defining abstract base classes.

These are the steps to create an abstract class in Python:

  1. Import the ABC class from the abc module.
  2. Create a new class that inherits from ABC.
  3. Define abstract methods using the @abstractmethod decorator.
from abc import ABC, abstractmethod

class AbstractClassName(ABC):
@abstractmethod
def abstract_method_name(self):
pass

For example:

from abc import ABC, abstractmethod

# Abstract base class
class Polygon(ABC):

@abstractmethod
def no_of_sides(self):
pass

# Concrete subclass
class Triangle(Polygon):

def no_of_sides(self):
return 3

# Attempting to instantiate the abstract class will raise an error
# polygon = Polygon() # This would raise a TypeError
triangle = Triangle() # This is fine, Triangle is a concrete class
print(triangle.no_of_sides()) # Output: 3