subscripting with 2 arguments in python

2.8k views Asked by At

Assume I have a class X which has 2 attributes : i and j.

I want to have :

x = X((1,2,3),(2,3,4)) #this would set i to (1,2,3) and j to (2,3,4)

I now want subscripting to work in the following way :

a, b = x[1,2] #a should now be 2 and b should now be 3

At the moment I'm trying this :

    def __getitem__(self, i, j):
        return self.x[i] , self.y[j]

However this keeps giving me the error that getitem takes in exactly 3 arguments but 2 is given (when I try to print out x[1,2] for instance)

1

There are 1 answers

6
Cat Plus Plus On BEST ANSWER

Comma is the tuple packing operator. x[1, 2] calls x.__getitem__((1, 2)).

def __getitem__(self, ij):
   i, j = ij
   return self.x[i], self.y[j]