The `@abc.abstractmethod` decorator in Python is used to define an...

January 2, 2025 at 12:55 PM

@abc.abstractmethod

The @abc.abstractmethod decorator in Python is used to define an abstract method inside an abstract base class (ABC).

  • Abstract methods: These are methods that are declared but have no implementation in a base class. Any subclass that inherits from the abstract base class is required to implement the abstract method.

  • abc module: This is a built-in Python module for defining abstract base classes.

When you apply the @abc.abstractmethod decorator to a method, it marks the method as abstract, ensuring that any concrete subclass must implement the method; otherwise, the subclass cannot be instantiated.

Example:

from abc import ABC, abstractmethod

class MyAbstractClass(ABC):
    @abstractmethod
    def my_abstract_method(self):
        pass

class MyConcreteClass(MyAbstractClass):
    def my_abstract_method(self):
        print("Implemented in the concrete class")

# The following will result in an error:
# my_instance = MyAbstractClass()  # Error: Can't instantiate abstract class

# Correct usage:
my_instance = MyConcreteClass()
my_instance.my_abstract_method()  # Output: Implemented in the concrete class

Key Points:

  • The @abc.abstractmethod ensures that the method must be implemented in subclasses.
  • Abstract base classes cannot be instantiated directly.
  • If a subclass doesn't implement all abstract methods, it also becomes abstract and cannot be instantiated.
Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node