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>

>>> 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

>>> 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
Rick Donato

Want to become a programming expert?

Here is our hand-picked selection of the best courses you can find online:
Python Zero to Hero course
Python Pro Bootcamp
Bash Scripting and Shell Programming course
Automate with Shell Scripting course
The Complete Web Development Bootcamp course
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial