Abstract classes: Force a class to implement methods.

Abstract classes can contain abstract methods: methods without an implementation.
Objects cannot be created from an abstract class. A subclass can implement an abstract class.

Related course: Complete Python Bootcamp: Go from zero to hero in Python 3

Abstract methods

But why?

If you have many objects of a similar type, you can call them in a similar fashion.

Imagine having classes like Truck, Car and Bus. They would all have methods like Start, Stop, Accelerate. An abstract class (Automobile) can define these abstract methods.


Visually that looks like:
abstract class

When a new class is added, a developer does not need to look for methods to implement. He/she can simply look at the abstract class.

If one of the sub classes (Truck, Car, Bus) misses an implementation, Python automatically throws an error.

Abstract class example

Create an abstract class: AbstractAnimal. In the abstract class we only define the methods without an implementation.

You can then create concrete classes: classes containing an implementation. Let’s create a class Duck which implements the AbstractAnimal. We use the same methods, but now add an implementation.

import abc

class AbstractAnimal(object):
__metaclass__ = abc.ABCMeta

def walk(self):
''' data '''

def talk(self):
''' data '''

class Duck(AbstractAnimal):
name = ''

def __init__(self, name):
print('duck created.')
self.name = name

def walk(self):

def talk(self):

obj = Duck('duck1')

If we forget to implement one of the abstract methods, Python will throw an error.

Traceback (most recent call last):
File "abst.py", line 27, in <module>
obj = Duck('duck1')
TypeError: Can't instantiate abstract class Duck with abstract methods walk

This is how you can force classes to have methods. Those methods need to be defined in the abstract class.