python - When subclassing a numpy ndarray, how can I modify __getitem__ properly? -


i attempting subclass numpy's ndarray. in subclass, called myclass, i've added field called time parallel array main data.

my goal following: suppose make instance of myclass, let's call mc. slice mc, instance mc[2:6], , want resulting object contain not sliced np array, correspondingly sliced time array.

here attempt:

class myclass(np.ndarray):     def __new__(cls, data, time=none):         obj = np.asarray(data).view(cls)         obj.time = time         return obj     def __array_finalize__(self, obj):         setattr(self, 'time', obj.time)     def __getitem__(self, item):         #print item #for testing         ret = super(myclass, self).__getitem__(item)         ret.time = self.time.__getitem__(item)         return ret 

this not work. after many hours of messing around, realized because when call mc[2:6], __getitem__ called multiple times. first when called, item variable, expected, slice(2,6,none). then, line containing super(myclass, self)... calls same function again, presumably go retrieve individual elements of slice.

the issue supplies __getitem__ strange set of parameters, negative numbers. in example of mc[2:6], calls method 4 more times, item values of -4, -3, -2, , -1.

as can see, makes impossible me adjust ret.time variable, since attempts modify multiple times, nonsensical indices.

i have tried working around in many ways, including copying object , editing copy instead, taking various views of object, , many other hacks, none seem overcome issue __getitem__ repeatedly called negative indices not line requested slice.

any or explanations going on appreciated.

as want update time on slices, try

if isinstance(item, slice):     ret.time = self.time.__getitem__(item) 

in __getitem__ method.

then time-adjusting code called once per slicing , never executed when getting single item array.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -