Abstract classes using collections.abc
The abstract base classes module is one of the most useful and most used examples of metaclasses in Python, as it makes it easy to ensure that a class adheres to a certain interface without a lot of manual checks. We have already seen some examples of abstract base classes in the previous chapters, but now we will look at the inner workings of these and the more advanced features, such as custom ABCs.
Internal workings of the abstract classes
First, let's demonstrate the usage of the regular abstract base class:
>>> import abc >>> class Spam(metaclass=abc.ABCMeta): ... ... @abc.abstractmethod ... def some_method(self): ... raise NotImplemented() >>> class Eggs(Spam): ... def some_new_method(self): ... pass >>> eggs = Eggs() Traceback (most recent call last): ... TypeError: Can't instantiate abstract class Eggs with abstract methods some_method >>> class Bacon(Spam): ....