Introduction

Learn about the concept of abstract base classes in Python.

Overview

We often need to distinguish between concrete classes with a complete set of attributes and methods, and an abstract class that is missing some details. This parallels the philosophical idea of abstraction as a way to summarize complexities. We might say that a sailboat and an airplane have a common, abstract relationship of being vehicles, but the details of how they move are distinct.

Possible approaches for similar items

In Python, we have two approaches to defining similar things:

  • Duck typing: When two class definitions have the same attributes and methods, then instances of the two classes have the same protocol and can be used interchangeably. We often say, “When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.”

  • Inheritance: When two class definitions have common aspects, a subclass can share common features of a superclass. The implementation details of the two classes may vary, but the classes should be interchangeable when we use the common features defined by the superclass.

We can take inheritance one step further. We can have abstract superclass definitions: this means they aren’t directly useable by themselves, but can be used through inheritance to create concrete classes.

We must acknowledge a terminology problem around the terms base class and superclass. This is confusing because they’re synonyms. There are two parallel metaphors here, and we flip back and forth between them. Sometimes, we’ll use the “base class is a foundation” metaphor, where another class builds on it via inheritance. Other times, we’ll use the “concrete class extends a superclass” metaphor. The super class is superior to the concrete class; it’s typically drawn above it on a UML class diagram and needs to be defined first. For example:

Get hands-on with 1400+ tech skills courses.