Key 6: Making interfaces for conformity.
Abstract classes are available via the standard abc
library package. They are useful for the definition of interfaces and common functionality. These abstract classes can implement a portion of the interface and make the rest of the API mandatory for subclasses by defining their methods as abstract. Also, classes can be turned into subclasses of the abstract class by simply registering them. These classes are useful to make a set of classes conform to a single interface. Here is how to use them. Here, worker class defines an interface with two methods, do and is_busy
, which each type of worker must implement. ApiWorker
is the implementation for this interface:
>>> from abc import ABCMeta, abstractmethod >>> class Worker(metaclass=ABCMeta): ... @abstractmethod ... def do(self, func, args, kwargs): ... """ work on function """ ... @abstractmethod ... def is_busy(self,): ... ""...