0

I'm trying to define a wrapper class having an attribute of type numpy.ndarray. That attribute must be initialised by calling __init__().

The script runs as expected for 1D arrays. However, in the case of multi-dimensionnal arrays, python returns the following error : only length-1 arrays can be converted to Python scalars

import numpy as np

class myArr(np.ndarray):
    def __init__(self,Arr):
        self.Arr = Arr

npArr = np.zeros((3)) # works
#npArr = np.zeros((3,5)) # does not work
print npArr

wrappedArr = myArr(npArr)
print wrappedArr.Arr

What is happening here ?

python 2.7.6, numpy 1.8.2

1 Answer 1

1

If you just want to have an attribute of type ndarray is there any specific reason you inherit from it?

I'd say that by subclassing ndarray and overriding __init__ you're messing with numpy's initialisation process, thus generating the error you're seeing.

See the numpy docs about Subclassing ndarray for more info.

Inheriting from object (converting MyArr to a regular new-style class) solves your problem:

import numpy as np

class MyArr(object):
    def __init__(self, arr):
        self.arr = arr

np_arr_1 = np.zeros((3))
np_arr_2 = np.zeros((3, 5))

wrapped_arr_1 = MyArr(np_arr_1)
wrapped_arr_2 = MyArr(np_arr_2)

print wrapped_arr_1.arr
print wrapped_arr_2.arr
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your answer ! The reason why I am implementing this wrapper class is that I have a code where numpy.roll() is very often called, usually multiple times in a single code line. In order to improve code readability, I would like to define a __call__() method as a replacement. It would be defined something like __call__(i,j): numpy.roll(self,[i,j]). Do you think that's the suitable approach ?
I don't think you need to go through the hassle of subclassing ndarray, just call numpy.call using self.arr instead of self

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.