Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python overloading multiple getitems / index requests

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__() method, but what about the second.

I thought I could achieve this by having a helper class which 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]

This seems a little too homebrewed... What is the python way to achieve this?

like image 779
jsj Avatar asked Jun 12 '12 16:06

jsj


People also ask

What is the most popular form of operator overloading in Python?

A very popular and convenient example is the Addition (+) operator. Just think how the '+' operator operates on two numbers and the same operator operates on two strings. It performs “Addition” on numbers whereas it performs “Concatenation” on strings.

How do you overload operators in Python?

In Python, overloading is achieved by overriding the method which is specifically for that operator, in the user-defined class. For example, __add__(self, x) is a method reserved for overloading + operator, and __eq__(self, x) is for overloading == .

Which conversion function Cannot be overloaded in a class in Python?

Python does not limit operator overloading to arithmetic operators only. We can overload comparison operators as well.

Which operator is overloaded by the OR () function in Python?

Which operator is overloaded by the __or__() function? Explanation: The function __or__() overloads the bitwise OR operator |.


2 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
like image 153
bpgergo Avatar answered Sep 30 '22 18:09

bpgergo


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.

like image 31
martinRSnilsson Avatar answered Sep 30 '22 19:09

martinRSnilsson