0

Two arguments in __getitem__

I'm creating a Matrix Class in Python and created a __getitem__ method, that gets i and j and return the [i][j] item. So I wrote "def __getitem__(i, j):" But when I try to use the indexer, (matrix[0, 0]), the interpreter returns TypeError: missing required positional argument j

10th Jan 2021, 3:36 PM
Levi Oliveira Matias
Levi Oliveira Matias - avatar
2 Antworten
+ 3
Levi Oliveira Matias only one argument is passed to __getitem__, no matter how many arguments you pass into the index. When you pass in more than one argument while indexing, the arguments are passed in as a tuple. For example, instance[0] will pass 0 to __getitem__. But instance[1, 2] will pass (1, 2), a tuple, to __getitem__. See this example https://code.sololearn.com/cg8P87t26Tp8/?ref=app
10th Jan 2021, 5:47 PM
XXX
XXX - avatar
+ 2
Do you mean " matrix[0][0] " to get the first element of the first element of a 2dimensional array? Then your matrix must have self parameter as the first parameter and index as the second parameter: def __getitem__(self, index): return Matrix.array[index] Take a look at this for example: https://code.sololearn.com/ca13A15a22a8
10th Jan 2021, 3:56 PM
noteve
noteve - avatar