Python - Slicing and Indexing in Python 2.X

Introduction

In Python 2.X only, classes can define __getslice__ and __setslice__ methods to intercept slice fetches and assignments specifically.

If defined, these methods are passed the bounds of the slice expression.

__getslice__ and __setslice__ methods are preferred over __getitem__ and __setitem__ for two-limit slices.


c:\python27\python 
class Slicer: 
   def __getitem__(self, index):     print index 
   def __getslice__(self, i, j):     print i, j 
   def __setslice__(self, i, j,seq): print i, j,seq 

print( Slicer()[1] )        # Runs __getitem__ with int, like 3.X 
print( Slicer()[1:9] )      # Runs __getslice__ if present, else __getitem__ 
print( Slicer()[1:9:2] )    # Runs __getitem__ with slice(), like 3.X!