2

How can I implement a customized list so that I can override the implementation of list[a:b]?

Thanks in advance!

  • 2
    I think your problem is not knowing the word for it. You need an __indexer__ . See [the official documentation](http://docs.python.org/2/reference/datamodel.html#emulating-container-types). – Benjamin Gruenbaum Jul 15 '13 at 11:04
  • Related link: http://docs.python.org/2/reference/datamodel.html#specialnames – Bakuriu Jul 15 '13 at 11:05

2 Answers2

5

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

Define the __*item__() methods to customize indexing.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358