Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

An abstract class in Python is a class that cannot be instantiated directly and serves as a strict blueprint for other classes. It enforces an interface by defining abstract methods—method signatures that lack a required implementation in the base class. Concrete subclasses inheriting from the abstract class are strictly required to override and implement all abstract methods before they can be instantiated. Python does not support abstract classes at the language-syntax level by default; instead, it provides this functionality through the standard library’s abc (Abstract Base Classes) module.

Core Implementation

To create an abstract class, the class must inherit from ABC (or use ABCMeta as its metaclass) and utilize the @abstractmethod decorator for the methods that subclasses must implement.
from abc import ABC, abstractmethod

class AbstractProcessor(ABC):
    
    @abstractmethod
    def process_payload(self, payload: dict) -> bool:
        """Subclasses must implement this method."""
        pass

    def validate_schema(self, payload: dict) -> bool:
        """Concrete methods are fully supported in abstract classes."""
        return isinstance(payload, dict)

Instantiation Rules

The Python interpreter enforces abstract class constraints at instantiation time, not at class definition time.
  1. Direct Instantiation: Attempting to instantiate a class that inherits from ABC and contains at least one @abstractmethod raises a TypeError.
  2. Incomplete Subclasses: If a subclass inherits from an abstract class but fails to override all abstract methods, the subclass itself becomes abstract. Attempting to instantiate it will also raise a TypeError.

# 1. Direct instantiation fails

# processor = AbstractProcessor()  

# TypeError: Can't instantiate abstract class AbstractProcessor with abstract method process_payload

class IncompleteProcessor(AbstractProcessor):
    pass


# 2. Incomplete subclass instantiation fails

# incomplete = IncompleteProcessor() 

# TypeError: Can't instantiate abstract class IncompleteProcessor with abstract method process_payload

class ConcreteProcessor(AbstractProcessor):
    def process_payload(self, payload: dict) -> bool:
        return True


# 3. Concrete subclass instantiation succeeds
valid_processor = ConcreteProcessor()

Abstract Properties

The @abstractmethod decorator can be combined with other decorators, such as @property, @classmethod, or @staticmethod, to enforce specific method types. When stacking decorators, @abstractmethod must be applied as the innermost decorator (closest to the function definition).
from abc import ABC, abstractmethod

class AbstractConnection(ABC):
    
    @property
    @abstractmethod
    def connection_string(self) -> str:
        pass

class DatabaseConnection(AbstractConnection):
    
    @property
    def connection_string(self) -> str:
        return "postgres://user:pass@localhost/db"

Base Implementations in Abstract Methods

Unlike interfaces in some statically typed languages, Python’s abstract methods can contain actual implementation code. While the subclass is still strictly required to override the method, it can invoke the abstract base method’s implementation using super().
from abc import ABC, abstractmethod

class BaseService(ABC):
    
    @abstractmethod
    def initialize(self):
        # Base implementation logic
        self.is_ready = False
        print("Base initialization complete.")

class ConcreteService(BaseService):
    
    def initialize(self):
        # Overriding is mandatory, but we can call the base logic
        super().initialize()
        self.is_ready = True
        print("Concrete initialization complete.")
Master Python with Deep Grasping Methodology!Learn More