Python overloading multiple getitems / index requests

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

    This question is quite old, but I'll add my answer anyway for newcomers.
    I ran into this need myself, and here's 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
    

    Notice that this will not work for single access!
    So, for example, if you want to use something of the form g[0] to get [0,1,2] it will not work, and instead you'll get nonsensical result (the object itself).

    0 讨论(0)
  • 2021-02-06 02:34

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

    and access the object override: instance[[2,3]]
    or instance[(2,3)]

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题