python - How do I override the [] operator as in list[1:10]? -


this question has answer here:

how can implement customized list can override implementation of list[a:b]?

thanks in advance!

implement __getitem__ hook; in case of slice slice object passed in.

a simple version be:

def __getitem__(self, index):     if isinstance(index, slice):         return [self[i] in range(*slice.indices(len(self)))]     return self._internal_sequence[index] 

note slice assignment , slice deletion must implement __setitem__ , __delitem__ hooks.

when overriding existing container types, you'll have handle __getslice__ method; deprecated python 2 types still implement it. again, there corresponding __setslice__ , __delslice__ hooks slice assignment , deletion too.


Comments