From: Pierre GM <pgm...@gm...> - 2006-10-20 01:23:38
|
> > >class InfoArray(N.ndarray): > > > def __new__(info_arr_cls,arr,info={}): > > > info_arr_cls.info = info > > > return N.array(arr).view(info_arr_cls) > > One has to be careful of this approach. It ads *the same* information > to all arrays, i.e. Indeed. That's basically why you have to edit your __array_finalize__ . class InfoArray(N.ndarray): def __new__(info_arr_cls,arr,info={}): info_arr_cls._info = info return N.array(arr).view(info_arr_cls) def __array_finalize__(self, obj): if hasattr(obj,'info'): self.info = obj.info else: self.info = self._info return OK, so you end up w/ two attributes 'info' and '_info', the latter having the info you want, the latter playing a temporary placeholder. That looks a bit overkill, but that works pretty nice. a = InfoArray(N.array([1,2,3]),{1:1}) b = InfoArray(N.array([1,2,3]),{1:2}) assert a.info=={1:1} assert b.info=={1:2} assert (a+1).info==a.info assert (b-2).info==b.info |