[SciPy-user] overriding __getitem__

Stefan Seefeld seefeld@sympatico...
Tue Apr 8 11:41:43 CDT 2008

Michael Hearne wrote:

> --------------------------------------------------------------------------------------------
> import numpy
> class Sequence:
>     def __init__(self):        self.data = 
> numpy.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
>     def __getitem__(self,key1,key2):        if isinstance(key1,int) and 
> isinstance(key2,int):            return(self.data[key1,key2])
> if __name__ == "__main__":    s = Sequence()   
>  s[2,2]--------------------------------------------------------------------------------------------However, 
> I get the error:"TypeError: __getitem__() takes exactly 3 arguments (2 
> given)"
> Isn't self an implied argument since __getitem__ is a class method?
> Is this the wrong way to attain the interface I want?

I did the following little experiment:

class Sequence:
     def __getitem__(self, *args): print 'getitem', args

s = Sequence()

The above shows that 's[1,2]' will pass a single argument: a '(1,2)' 
tuple, while 's[1:2,1:2]' will pass two arguments (two slice objects).
This is with python 2.5. A quick search didn't reveal any documentation 
of this behavior.

This suggests that you may rewrite your definition of __getitem__ to be 
more flexible in its expectations as to number and type of arguments.

(I'm not sure what makes you think __getitem__ is a class method. It's 
an ordinary attribute, expecting the first argument to be the object 
reference, just what you pass above.)




       ...ich hab' noch einen Koffer in Berlin...

More information about the SciPy-user mailing list