Python overloading multiple getitems / index requests

后端 未结 4 557
无人及你
无人及你 2021-02-06 01:54

I have a Grid class which I want to access using myGrid[1][2]. I know I can overload the first set of square brackets with the __getitem__()

4条回答
  •  失恋的感觉
    2021-02-06 02:54

    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
    

提交回复
热议问题