How can I implement a customized list so that I can override the implementation of list[a:b]
?
Thanks in advance!
How can I implement a customized list so that I can override the implementation of list[a:b]
?
Thanks in advance!
Implement the __getitem__
hook; in case of a slice a slice
object is passed in.
A simple version could be:
def __getitem__(self, index):
if isinstance(index, slice):
return [self[i] for i in range(*slice.indices(len(self)))]
return self._internal_sequence[index]
Note that for slice assignment and slice deletion you must also implement the __setitem__
and __delitem__
hooks.
When overriding existing container types, you'll also have to handle the __getslice__
method; it is deprecated but Python 2 types still implement it. Again, there are corresponding __setslice__
and __delslice__
hooks for slice assignment and deletion too.
Define the __*item__()
methods to customize indexing.