Creating Our Own Abstract Base Class

Learn how we can create our own abstract base classes in Python.

Define using duck typing

We have two general paths to creating similar classes: we can leverage duck typing or define common abstractions. When we leverage duck typing, we can formalize the related types by creating a type hint using a protocol definition to enumerate the common methods or a Union[] to enumerate the common types.

An almost unlimited number of influencing factors suggest one or the other approach. While duck typing offers the most flexibility, we may sacrifice the ability to use mypy. An abstract base class definition can be wordy and potentially confusing.

Example

We’ll tackle a small problem. We want to build a simulation of games that involve polyhedral dice. The dice include four, six, eight, twelve, and twenty sides. The six-sided dice are conventional cubes. Some sets of dice include 1010-sided dice, which are cool, but aren’t – technically – a regular polyhedron; they’re two sets of five “kite-shaped” faces.

One question that comes up is how best to simulate rolls of these different shaped dice. There are three readily available sources of random ...