Python overloads multiple getitems / index requests

I have a Grid class that I want to access with using myGrid[1][2] . I know that I can overload the first set of square brackets with the __getitem__() method, but what about the second.

I thought I could achieve this by having a helper class that also implements __getitem__ , and then:

 class Grid: def __init__(self) self.list = A TWO DIMENSIONAL LIST ... def __getitem__(self, index): return GridIndexHelper(self, index) class GridIndexHelper: def __init__(self, grid, index1): self.grid = grid self.index1 = index1 .... def __getitem__(self, index): return self.grid.list[self.index1][index] 

It seems like this is too much homegrown ... What is the python way to achieve this?

+7
source share
4 answers
 class Grid: def __init__(self): self.list = [[1,2], [3,4]] def __getitem__(self, index): return self.list[index] g = Grid(); print g[0] print g[1] print g[0][1] 

prints

 [1, 2] [3, 4] 2 
+10
source

As far as I know, the way anime is mentioned is the only way.

Example:

 class Grid(object): def __init__(self): self.list = [[1, 2], [3, 4]] def __getitem__(self, index): return self.list[index[0]][index[1]] if __name__ == '__main__': mygrid = Grid() mygrid[1, 1] #How a call would look 

Print: 4

It doesn't work exactly the way you want it to, but it does the trick in my eyes.

+4
source

you can make an index into a tuple: def getitem (self, indexTuple): x, y = indexTuple ...

and access an object override: for example, [[2,3]]
or instance [(2,3)]

0
source

This question is pretty old, but I will add my answer for beginners anyway.
I ran into this problem myself, and here is a solution that worked for me:

 class Grid: def __init__(self): self.matrix = [[0,1,2],[3,4,5],[6,7,8]] self.second_access = False def __getitem__(self, key): if not self.second_access: self.first_key = key self.second_access = True return self else: self.second_access = False return self.matrix[self.first_key][key] g = Grid() print(g[1][2]) # 5 print(g[0][1]) # 1 print(g[2][0]) # 6 

Please note that this will not work for single access!
So, for example, if you want to use something from the form g[0] to get [0,1,2] , this will not work, and instead you will get a meaningless result (the object itself).

0
source

All Articles