1

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 Answer 1

7

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]
Sign up to request clarification or add additional context in comments.

6 Comments

wow, that was quick..Could you give me a pointer to where this is explained in more detail?
@ArnabDatta: T *ptr = &internet;. Seriously, though, I'd imagine tuples are explained in any Python tutorial.
call me a noob, but I tried searching the internet for getitem with multiple params, subscripting with multiple params, and looked through explanations of the getitem method without any luck. The fact that comma is the tuple packing operator is not obvious to someone new to python, so the sarcasm isnt exactly well recieved in this case.
@ArnabDatta - tuple packing and unpacking isn't specific to __getitem__ and is described somewhat here: docs.python.org/tutorial/…
@ArnabDatta: This is not related to __getitem__. __getitem__ takes an object (as in x[obj] is equivalent to x.__getitem__(obj)), you pass a tuple here (I'm pretty sure the official tutorial remarks that it's comma that creates a tuple, not parenthesis). There's nothing more to it. Also, joke and sarcasm is not the same thing.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.