In Python, it is often useful to create an abstract class to serve as a “skeleton” for a subclass. However, Python does not enforce abstract base class inheritance by default, meaning subclasses are not required to implement abstract methods of the parent class. Read on to learn about creating abstract classes in Python.

Now I will show you how to implement a simple and effective base class using the abc standard library module in Python 3.4. The abc module was added in Python 2.6 as defined by this proposal: PEP 3119.

In our base class, we have mandated the logic of the initializer to store 2 operand variables. Using the @abstractmethod decorator, we enforce implementation of the “execute” method for subclasses that inherit the AbstractOperation class. Forcing the implementation of parent methods in derived classes allows us to separate the interface from implementation details.

When attempting to instantiate the base class, we get the following exception:

Let’s try creating a concrete class, without implementing the “execute” method.

Under the hood:
Before the ConcreteOperation concrete class is instantiated, the ConcreteOperation metaclass verifies all @abstractmethod decorated methods have been implemented. Just as object classes define how an instance of a class behaves, metaclasses define how a class behaves.

Now let’s create a few concrete classes that properly implement the “execute” method.

Success! Our derived classes satisfy the interface dictated by the parent object.

Enforcing these checks upon object instantiation provides an effective way to make sure concrete classes are properly implemented. I find this pattern useful when employing the strategy and template method design patterns.

The dynamic nature of Python is extremely powerful but lacks some useful type safety features of statically typed languages. Using the abc module can help programmers establish rigid contracts between base and concrete classes.


Get our free DevOps course delivered straight to your inbox! You’ll learn these tactics:

  • Docker Tips and Tricks
  • Agile Methodologies
  • Documentation and Tools Hacks
  • Containerization vs Virtualization

These DevOps lessons will help your team collaborate and become more agile, so sign up now!

Related Posts

Related Topics & Tags: Industry Thoughts Quick Tips

About Travis Cunningham

Software Engineer. Loves community and open source.

Leave a Reply

Your email address will not be published. Required fields are marked *