Explain Codes LogoExplain Codes Logo

Is it possible to make abstract classes in Python?

python
abstract-classes
abc-module
inheritance
Nikita BarsukovbyNikita Barsukov·Dec 20, 2024
TLDR

Python offers a way to wrap abstract classes using the abc module and the @abstractmethod. By subclassing ABC, and decorating methods with @abstractmethod, you ensure they're required to be implemented in the child classes.

from abc import ABC, abstractmethod class AbstractShape(ABC): @abstractmethod def area(self): pass

You won't dare instantiate AbstractShape until area is well-defined!

Abstract class: An overview

In essence, abstract classes serve as frameworks for concrete classes, stipulating a method set that all derived classes must implement. Deriving from AbstractShape is like making a pact to offer specific method implementations.

Using ABC and ABCMeta

The ABC platform arrived with Python 3.4+, making it easier to declare abstract classes:

from abc import ABC class MyAbstractClass(ABC): pass

For the under 3.4 gang, use ABCMeta as your metaclass:

from abc import ABCMeta class MyAbstractClass(metaclass=ABCMeta): pass

Method enforcement: The @abstractmethod

Abstract methods are designated using the @abstractmethod decorator. A subclass transforms into a concrete class once it implements all abstract methods — your shield against chaotic design.

Abstract methods and properties

You're not limited to methods! Define abstract properties using @abstractmethod and @property decorators, guiding subclasses to follow certain property behaviors.

Protecting from rogue instantiation

Without a full implementation of all the abstract methods, instantiation of a class results in a TypeError, blocking unauthorized life breath to classes that serve only as specifications.

Throwing the NotImplementedError

Prior to abc module, methods not meant for direct invocation would raise NotImplementedError. However, the abc module brings clearer structure to abstraction, without getting our hands dirty with raise statements.

Embracing the abstract world

When you extend an abstract class, your subclass better step up and implement all the abstract methods. Unfortunately, many new devs half-bake this step, leading to runtime errors when they shouldn't exist.

Tagging with other decorators

Let @abstractmethod mingle! Use it in combination with @staticmethod, @classmethod, and @property to make the class-level features concrete.

Understanding inheritance and instantiation

Inheritance is messy! Always handle __new__ overrides with care, especially when dealing with instantiation of child classes.

Instances with character

Concrete child classes derived from an abstract class can be instantiated. This enforces consistent behaviour of different object types unified under the abstract class interface.

Guarding against base class instantiation

One can take this a step further by using __init__ to check the type of self. If someone tries instantiating the abstract base class, raise an exception!

The skeleton provided by ABCs

Abstract Base Classes (ABCs) allow developers to lay out a required structure for any sub-class. This brings a semblance of order, enforcement of method signatures and expected behaviours, while freedom for implementation remains.

BusinessException: Real-world implications

Abstract classes help construct scalable architectures, providing a clear set of method definitions and enforced interfaces. This reduces bug count and increases code complexity with a lot more clarity.

Undisputable clear error messages

One major advantage of Python's approach to abstract classes is the early-stage, comprehensive error messages. This helps developers identify and address subclass issues immediately upon instantiation.