Python overloading multiple getitems / index requests

后端 未结 4 642
无人及你
无人及你 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:53

    As far as I know the way anajem mentions 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
    

    Prints: 4

    Does not operate exactly as you want it to but does the trick in my eyes.

提交回复
热议问题