[Numpy-discussion] how add new attribute to a numpy array object ?

Filip Wasilewski filipwasilewski at gmail.com
Sun Jul 23 15:02:50 CDT 2006


On 7/23/06, Eric Firing <efiring at hawaii.edu> wrote:
> Sebastian Haase wrote:
> > Hi,
> > I have a (medical) image file.
> > I wrote a nice interface based on memmap using numarray.
> > The class design I used  was essentially to return a numarray array
> > object with a new "custom" attribute giving access to special
> > information about the base file.
> >
> > Now with numpy I noticed that a numpy object does not allow adding new
> > attributes !! (How is this ? Why ?)
> >
> > Travis already suggested (replying to one of my last postings) to create
> > a new sub class of numpy.ndarray.
> >
> > But how do I initialize an object of my new class to be "basically
> > identically to" an existing ndarray object ?
> > Normally I could do
> > class B(N.ndarray):
> >     pass
> > a=N.arange(10)
> > a.__class__ = B
>
> Isn't this what you need to do instead?
>
> In [1]:import numpy as N
>
> In [2]:class B(N.ndarray):
>     ...:    pass
>     ...:
>
> In [3]:a = B(N.arange(10))

It won't work like that. The constructor for the ndarray is:

  |  ndarray.__new__(subtype, shape=, dtype=int_, buffer=None,
  |                  offset=0, strides=None, fortran=False)

so you will get either an exception caused by inappropriate shape
value or completely wrong result.

>>> numpy.ndarray([1,2])
array([[10966528, 18946344]])
>>> numpy.ndarray([1,2]).shape
(1, 2)
>>> numpy.ndarray(numpy.arange(5))
array([], shape=(0, 1, 2, 3, 4), dtype=int32)

And this is a thing you souldn't do rather than a bug.

To create an instance of ndarray's subclass B from ndarray object, one
need to call the ndarray.view method or the ndarray.__new__
constructor explicitly:

class B(numpy.ndarray):
	def __new__(subtype, data):
		if isinstance(data, B):
			return data
		if isinstance(data, numpy.ndarray):
			return data.view(subtype)
		arr = numpy.array(data)
		return numpy.ndarray.__new__(B, shape=arr.shape, dtype=arr.dtype, buffer=arr)

A good example of subclasing ndarray is the matrix class in
core/defmatrix.py (SVN version).

cheers,
fw




More information about the Numpy-discussion mailing list