Development Category (English)728x90

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.

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.

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

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

Previous Post
Next Post

Leave a Reply