Skip to content
Advertisement

How to make a __getitem__ method that allows list[][] indexing (2D)

I am trying to make a getitem method where I can use [][] to get an element from and array I have made. The method I came across is this:

JavaScript

The problem with this is that I only can access the array by using a tuple, like array[1,0]. What I want is to be able to do this: array[1][0].

Im not sure how to pass these two arguments inside the getitem method since it only can take one at a time.

Any tips on how to make it work? Thank you :)

Advertisement

Answer

In Python, two pairs of square brackets mean twice indexes, so array[1][0] is equivalent to:

JavaScript

After one index, your twoDim can return the object that can be indexed again, so if the index has only one element, you can apply it to twoDim directly:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement