'Attempting to use np.insert in a created class which has subscripts yields "object does not support item assignment" debug

I have defined my own class which takes in any matrix and is defined in such a way to convert this matrix into three numpy arrays inside a parenthesis (which I assume means it's a tuple). Furthermore, I have added a getitem method which allows output arrays to be subscript-able just like normal arrays.

My class is called MatrixConverter, and say x is some random matrix, then:

q=MatrixConverter(x)

Where q gives:

q=(array[1,2,3,4],array[5,6,7,8],array[9,10,11,12])

(Note that this is just an example, it does not produce three arrays with consecutive numbers)

Then, for example, by my getitem method, it allows for:

q[0] = array[1,2,3,4]
q[0][1] = 2

Now, I'm attempting to design a method to add en element into one of the arrays using the np.insert function such as the following:

class MatrixConverter
#some code here
def __change__(self,n,x):
    self[1]=np.insert(self[1],n,x)
return self

Then, my desired output for the case where n=2 and x=70 is the following:

In:q.__change__(2,70)
Out:(array[1,2,3,4],array[5,6,70,7,8],array[9,10,11,12])

However, this gives me a TypeError: 'MatrixConverter' object does not support item assignment.

Any help/debugs? Should I perhaps use np.concentate instead?

Thank you!



Solution 1:[1]

Change your method to:

def __change__(self,n,x):
    temp = np.insert(self[1],n,x)
    self[1] = temp
return self

This will help you distinguish between a problem with the insert and a problem with the self[1] = ... setting.

I don't think the problem is with the insert call, but you need to write code that doesn't confuse you on such matters. That's a basic part of debugging.

Beyond that you haven't given us enough code to help you. For example what's the "getitem".

Expressions like array[1,2,3,4] tell me that you aren't actually copying from your code. That's not a valid Python expression, or array display.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hpaulj