fir3net
PPS-Firenetbanner-780.5x190-30-03-17

Python - What are Abstract Classes?

An abstract class can be considered a blueprint for other classes, allowing you to mandate a set of methods that must be created within any child classes built from your abstract class.

Creation

Lets first look at how you create an abstract class. First we import abc, we define the class as a metaclass using the __metaclass__ magic attribute, we then decorate using @abc.abstractmethod.

import abc

class TestClass(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def set_total(self,input):
        """Set a value for instance."""
        return

    @abc.abstractmethod
    def get_total(self):
        """Get and return a value for instance."""
        return

Subclassing

Lets look at an abstract class in action.

First, if we go and build a child class from this base class, using the correct methods i.e abstract methods, we should see no problems. Like so,

class MyClass(TestClass):
    def set_total(self,x):
        self.total = x

    def get_total(self):
        return self.total

>>> m = MyClass()
>>> print m
<__main__.MyClass object at 0x100414910>

However if we create a child class with methods different to what was set within our abstract class, the class will not instantiate.
Notice how I have changed the name of the get_total method to xyz_get_total

class MyClass(TestClass):
    def set_total(self,x):
        self.total = x

    def xyz_get_total(self):
        return self.total

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

Abstract Class Instantiation

And finally there is one last point that I should highlight. Due to the fact that an abstract class is not an concrete class, it cannot be instantiated. Heres an example,

>>> t = TestClass()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: Can't instantiate abstract class TestClass with abstract methods get_total, set_total

Tags: Python

About the Author

RDonato

R Donato

Ricky Donato is the Founder and Chief Editor of Fir3net.com. He currently works as a Principal Network Security Engineer and has a keen interest in automation and the cloud.

You can find Ricky on Twitter @f3lix001