Handling slices

Alexander Schmolck a.schmolck at gmx.net
Sun Apr 6 22:54:17 EDT 2003


Francois Pinard <pinard at iro.umontreal.ca> writes:

> Hi, Python friends.
> 
> I'm currently using Python 2.2.1.  How does one support slices when given
> to __getitem__?  Suppose I get a slice object.  How can I use it to get
> a slice of a local array?  In other words, how one does apply a slice?

array[slice]

won't work for lists

> 
> The documentation says that __getslice__ is deprecated since 2.0, but then,
> I need an alternative way for using it.  What is it?

__getitem__

Here is a simple example:

class SliceMaker:
    """Convinience class to make slices."""
    def __getitem__(self, a): return a


>>> a = Numeric.array([1,2,3,4])
>>> a[SliceMaker()[3:1:-1]
array([4, 3])


alex




More information about the Python-list mailing list