Better Programming: Abstract Classes In Python
Jul 31, 2023
Abstract classes are a feature in Python that let us define interfaces for the components used in your program. But what exactly is an interface?
An interface is like a blueprint that specifies what capabilities classes of a certain type need to have. For instance, imagine we have a function that takes in some geometric shape as input and prints out its area. Something like this:
The area of various geometric shapes is computed differently. Imagine we define these two classes:
These two shapes each implement the area() method differently. So if we used them with a function printing area, it would use the right area calculation for that shape. But say you go to add a new shape but forget to actually implement the area() method on it.
If you passed that new shape to the function, you’d get an error since area() isn’t defined for that shape.
While this is a made up example, these kinds of errors can happen a lot in real programs. So, how can we force all shapes to implement the necessary area() method? Enter Abstract Classes.
To learn Python and build the skills to land your first job, check out our Professional Python Developer Bootcamp.
What are abstract classes?
These are classes that cannot be instantiated. In other words, you can’t create objects of an abstract class. The goal of these classes is to define functionality that their subclasses must implement.
In Python, abstract classes are available in the abc module. Using these classes, we are going to re-implement the previous example. Let's begin by creating our first abstract class. What do circles, squares and triangles have in common? They are all shapes. Shape is the general, abstract category that all these types belong to.
For that reason, we are going to define a new class called Shape as an abstract class with the functionality and properties that every shape should have (in our example, the area):
In the previous snippet, we imported the ABC class and the abstractmethod annotation from the abc module (as in abstract base class). To make the Shape class abstract, all we have to do is make it extend the ABC class. Now, if we try to create an instance of this class, we will get an error:
Inside this class, we have the area method annotated as abstractmethod, and the body of the method is left empty. The purpose of this is to delegate the implementation of this method to the subclasses that extend the Shape class. Let's create two subclasses, Circle and Square:
As you can see, these classes implement the area method in different ways, but when called by our print_area() function, each of these classes will use their own implementation of the area method to calculate this value:
However, if we create a subclass of Shape that does not implement this method, we will get an error:
By using an abstract class to define the functionality that every Shape should have, and then creating derived classes from it to define different kinds of shapes, we have made our code safer, easier to read and harder to break.
Our colleagues now know what is expected by a new implementation of a shape, without having to guess.
Benefits of using abstract classes
Using abstract classes (when necessary) can improve our code on several fronts:
Code reliability
By defining an interface and forcing the subclasses to implement it, you avoid errors where expected methods may be missing.
Polymorphism
The common interface allows you to swap implementations without causing problems, and that means you can select a different implementation depending on the context.
Loose coupling
Relying on interfaces rather than actual implementations adds a layer of separation between different parts of our code.
Organization
Abstract classes provide a way of structuring your classes that is very easy to understand.
Avoid code repetition
Abstract classes allow common method implementations to be defined once in the superclass rather than duplicated across subclasses. This avoids repetition and improves maintainability.
AI moves fast. We help you keep up with it.
Get a monthly selection of the most groundbreaking advances in the world of AI, top code repositories, and our best articles and tutorials.
We hate SPAM. We will never sell your information, for any reason.