In Python, collections are sequences such as lists and strings, mappings such as dictionaries, or sets. If we implement our own collection classes we can use special methods to make our collections usable with the same syntax and semantics as the built-in collection types. Table 3.3 lists the special methods common to collections, and in this section we discuss some of the specifics of each kind of collection.
In the case of sequences, it is common to implement_add_() and_radd_()
to support concatenation with +, and in the case of a mutable collection, to implement_iadd_(), for +=, too. Similarly, the_mul_() methods should be implemented to support * for repeating the collection. If an invalid index is given, we should raise an IndexError exception. In addition to special methods, a custom sequence collection ought to implement append(), count(), index(), insert(), extend(), pop(), remove(), reverse(), and sort().
Genera tor functions
Was this article helpful?