How to make a __getitem__ method that allows list[][] indexing (2D)
Question:
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:
def __getitem__(self, item):
x, y = item
return self.twoDim[x][y]
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 🙂
Answers:
In Python, two pairs of square brackets mean twice indexes, so array[1][0]
is equivalent to:
array.__getitem__(1).__getitem__(0)
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:
def __getitem__(self, item):
if not isinstance(item, tuple):
return self.twoDim[item]
x, y = item
return self.twoDim[x][y]
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:
def __getitem__(self, item):
x, y = item
return self.twoDim[x][y]
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 🙂
In Python, two pairs of square brackets mean twice indexes, so array[1][0]
is equivalent to:
array.__getitem__(1).__getitem__(0)
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:
def __getitem__(self, item):
if not isinstance(item, tuple):
return self.twoDim[item]
x, y = item
return self.twoDim[x][y]