I am trying to make a getitem method where I can use [][] to get an element from and array I have made. The method I came across is this:
JavaScript
x
4
1
def __getitem__(self, item):
2
x, y = item
3
return self.twoDim[x][y]
4
The problem with this is that I only can access the array by using a tuple, like array[1,0]. What I want is to be able to do this: array[1][0].
Im not sure how to pass these two arguments inside the getitem method since it only can take one at a time.
Any tips on how to make it work? Thank you :)
Advertisement
Answer
In Python, two pairs of square brackets mean twice indexes, so array[1][0]
is equivalent to:
JavaScript
1
2
1
array.__getitem__(1).__getitem__(0)
2
After one index, your twoDim
can return the object that can be indexed again, so if the index has only one element, you can apply it to twoDim
directly:
JavaScript
1
6
1
def __getitem__(self, item):
2
if not isinstance(item, tuple):
3
return self.twoDim[item]
4
x, y = item
5
return self.twoDim[x][y]
6