Slicing wrapped numpy arrays

Robert Kern robert.kern at gmail.com
Sun Jan 13 22:15:16 EST 2008


Martin Manns wrote:
> On Sun, 13 Jan 2008 16:03:16 -0600
> Robert Kern <robert.kern at gmail.com> wrote:
> 
>> 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
>>     ...:
> 
> I did that and got here:
> 
>> (slice(None, None, 2), slice(10, None, 10))
> 
> However, I still do not see how I get a Map object that employs a
> slice of the array without creating a new Map object.

That's because creating a new Map object is the right thing to do.

Instead of making Map.__init__() generate the map array from the dimensions, it 
should just take a preconstructed map array. You can use a @classmethod or just 
a factory function to provide an alternate constructor which builds a Map from 
the dimensions.

When designing classes, I usually try to do as little computation as possible in 
an __init__(). Doing a lot of stuff there limits the ways you can build the 
object later. For some classes, this doesn't matter a whole lot, but for data 
structures that can be sliced and concatenated or otherwise transformed, you 
really want that flexibility.

-- 
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




More information about the Python-list mailing list