Interface
An interface, for an object, is a set of methods and attributes on that object.
In Python, we can use an abstract base class to define and enforce an interface.
Using an Abstract Base Class
For example, say we want to use one of the abstract base classes from the collections
module:
If we try to use it, we get an TypeError
because the class we created does not support the expected behavior of sets:
So we are required to implement at least __contains__
, __iter__
, and __len__
. Let's use this implementation example from the documentation:
Implementation: Creating an Abstract Base Class
We can create our own Abstract Base Class by setting the metaclass to abc.ABCMeta
and using the abc.abstractmethod
decorator on relevant methods. The metaclass will be add the decorated functions to the __abstractmethods__
attribute, preventing instantiation until those are defined.
For example, "effable" is defined as something that can be expressed in words. Say we wanted to define an abstract base class that is effable, in Python 2:
Or in Python 3, with the slight change in metaclass declaration:
Now if we try to create an effable object without implementing the interface:
and attempt to instantiate it:
We are told that we haven't finished the job.
Now if we comply by providing the expected interface:
we are then able to use the concrete version of the class derived from the abstract one:
There are other things we could do with this, like register virtual subclasses that already implement these interfaces, but I think that is beyond the scope of this question. The other methods demonstrated here would have to adapt this method using the abc
module to do so, however.
Conclusion
We have demonstrated that the creation of an Abstract Base Class defines interfaces for custom objects in Python.
Last updated
Was this helpful?