Python

Abstract Base Classes

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: Python Beyond the Basics – Object-Oriented Programming

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.

truck.start()
truck.drive()
bus.start()
bus.drive()

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

@abc.abstractmethod
def walk(self):
''' data '''

@abc.abstractmethod
def talk(self):
''' data '''

class Duck(AbstractAnimal):
name = ''

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

def walk(self):
print('walks')

def talk(self):
print('quack')

obj = Duck('duck1')
obj.talk()
obj.walk()

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.

Previous Post Next Post

Cookie policy | Privacy policy | ©

OOP