Robert Kern
1/13/2008 10:03:00 PM
Martin Manns wrote:
> Hi,
>
> I have created a class that wraps a numpy array of custom objects. I
> would like to be able to slice respective objects (without copying the
> array if possible).
>
> I have browsed the doc and found some hints at __getitem__. However, I
> still do not grasp how to do it. How do I implement __getitem__
> correctly?
> mymap[10:20,15:20,:] # This line should work afterwards
The first thing you should do is simply implement a very basic, nonfunctional
version just to see what objects come in:
In [1]: class Sliceable(object):
...: def __getitem__(self, arg):
...: print arg
...:
From the output of that you should be able to figure out how to process each of
the various inputs that you want to handle.
In [2]: s = Sliceable()
In [3]: s[0]
0
In [4]: s[-1]
-1
In [5]: s[100]
100
In [6]: s[1:10]
slice(1, 10, None)
In [7]: s[1:10:2]
slice(1, 10, 2)
In [8]: s[1:10:-2]
slice(1, 10, -2)
In [9]: s[:10:2,10]
(slice(None, 10, 2), 10)
In [10]: s[:10:2,10:100:10]
(slice(None, 10, 2), slice(10, 100, 10))
In [11]: s[:10:2,10::10]
(slice(None, 10, 2), slice(10, None, 10))
In [12]: s[::2,10::10]
(slice(None, None, 2), slice(10, None, 10))
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco