0

I have built a wrapper around numpy array for simplification purposes I will display only the necessary part to show the error:

class Matrix(object): """wrap around numpy array """ def __init__(self, shape, fill_value): self.matrix = np.full(shape, fill_value) def __getitem__(self, a, b): return self.matrix[a, b] m = Matrix((10, 10), 5) print(m[5, 5]) 

the print statement generates the following error:

KeyError: __getitem__() takes exactly 3 arguments (2 given) 

what's the fix to access m using the [] operator like the follwing:

m[1, 1] 

2 Answers 2

2

the solution is to pass a tuple inside a variable like the following:

class Matrix(object): """wrap around numpy array """ def __init__(self, shape, fill_value): self.matrix = np.full(shape, fill_value) def __getitem__(self, a): # we could do also do return self.matrix[a[0], a[1]] return self.matrix[a] m = Matrix((10, 10), 5) print(m[5, 5]) 
Sign up to request clarification or add additional context in comments.

Comments

1

Currently, you have a class Matrix with an attribute matrix which is a numpy array. Therefore you would need to reference the attribute first and then pass the indices:

>>> m.matrix[5,5] 5 

At this point, you have not wrapped around a numpy array. Depending on what you want to do, this could be a step in the right direction:

class Matrix(np.ndarray): def __new__(cls, shape, fill_value=0): return np.full(shape, fill_value) >>> m = MyMatrix((10, 10), 5) >>> print(m[5, 5]) >>> 5 

However, this essentially does nothing more than m = np.full(shape, fill_value). I suppose you are going to want to add custom attributes and methods to a numpy array, in which you should check out this example in the numpy documentation.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.