abstract classes in python

Creating Abstract Classes in Python 3

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.

from abc import ABC, abstractmethodclass AbstractOperation(ABC):    def __init__(self, operand_a, operand_b):        self.operand_a = operand_a        self.operand_b = operand_b        super(AbstractOperation, self).__init__()        @abstractmethod    def execute(self):        pass

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:

>>> a = AbstractOperation(1, 2)Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: Can't instantiate abstract class AbstractOperation with abstract methods execute

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

class ConcreteOperation(AbstractOperation):    pass
>>> c = ConcreteOperation(1, 2)Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: Can't instantiate abstract class ConcreteOperation with abstract methods execute

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.

class AddOperation(AbstractOperation):    def execute(self):        return self.operand_a + self.operand_bclass SubtractOperation(AbstractOperation):    def execute(self):        return self.operand_a - self.operand_bclass MultiplyOperation(AbstractOperation):    def execute(self):        return self.operand_a * self.operand_bclass DivideOperation(AbstractOperation):    def execute(self):        return self.operand_a / self.operand_b
>>> operation = AddOperation(1, 2)>>> operation.execute()3>>> operation = SubtractOperation(8, 2)>>> operation.execute()6>>> operation = MultiplyOperation(8, 2)>>> operation.execute()16>>> operation = DivideOperation(8, 2)>>> operation.execute()4.0

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.

BECOME A DEVOPS PRO
FREE DEVOPS COURSE

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

SmartFile is a business file mangement platform that gives you more control, compliance and security.

TO SIGN UP