[Numpy-discussion] Overriding numpy.ndarray.__getitem__?
Wed Aug 17 14:25:33 CDT 2011
I have a subclass of ndarray which is built using using a stack of images.
Rather than store the image header information separately, I overrode
__getitem__ so that when the user indexes into the image cube a single image
a different object type (which includes the header information) is returned
def __getitem__(self, key):
"""Overiding indexing operation"""
if isinstance(key, int):
data = np.ndarray.__getitem__(self, key)
header = self._headers[key]
return SingleImage(data, header)
return np.ndarray.__getitem__(self, key)
Everything seems to work well, however, now when I try to combine that with
indexing into the other dimensions of a single image, errors relating to
numpy's array printing arise, e.g.:
>>> print imagecube[0,0:256,0:256]
/usr/lib/pymodules/python2.7/numpy/core/arrayprint.pyc in _formatArray(a,
format_function, rank, max_line_len, next_line_prefix, separator,
371 if leading_items or i != trailing_items:
372 s += next_line_prefix
--> 373 s += _formatArray(a[-i], format_function, rank-1,
374 " " + next_line_prefix, separator,
I think the problem has to do with how I am overriding __getitem__: I check
to see if the input is a single integer, and if it is, I return the new
object instance. This should only occur when something like "imagecube[n]"
is called, however, array2str ends up calling imagecube[x], even if the
original thing you are trying to print is something like
Any ideas? I apologize if the explanation is not very clear; I'm still
trying to figure out exactly what is going on.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the NumPy-Discussion