Implementing Custom Containers
Problem
You want to implement a custom class that mimics the behavior of a common built-in container type, such as a list or dictionary. However, you’re not entirely sure what methods need to be implemented to do it.
Solution
The collections
library defines a variety of abstract base classes
that are extremely useful when implementing custom container classes.
To illustrate: suppose you want your class to support iteration.
To do that, simply start by having it inherit from collections.Iterable
, as
follows:
import
collections
class
A
(
collections
.
Iterable
):
pass
The special feature about inheriting from collections.Iterable
is that
it ensures you implement all of the required special methods. If you don’t,
you’ll get an error upon instantiation:
>>>
a
=
A
()
Traceback (most recent call last):
File"<stdin>"
, line1
, in<module>
TypeError
:Can't instantiate abstract class A with abstract methods __iter__
>>>
To fix this error, simply give the class the required __iter__()
method and implement it as desired (see Recipes 4.2 and 4.7 in Python Cookbook, 3rd ed.).
Other notable classes defined in collections
include Sequence
,
MutableSequence
, Mapping
, MutableMapping
, Set
, and
MutableSet
. Many of these classes form hierarchies with increasing levels of functionality (e.g., ...
Get Implementing Custom Containers now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.