[SciPy-user] overriding __getitem__

Michael Hearne mhearne@usgs....
Tue Apr 8 11:51:47 CDT 2008


Stefan and Matthieu - Thanks for the responses.  I will work on my  
code as you suggest.

Stefan - I think I used "class method" inappropriately - I think the  
appropriate term is "instance method".

--Mike
On Apr 8, 2008, at 10:41 AM, Stefan Seefeld wrote:

> 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()
> s[1]
> s[1,2]
> s[1:2]
> ...
>
> 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.)
>
> HTH,
>
> 		Stefan
>
> -- 
>
>        ...ich hab' noch einen Koffer in Berlin...
> _______________________________________________
> SciPy-user mailing list
> SciPy-user@scipy.org
> http://projects.scipy.org/mailman/listinfo/scipy-user




------------------------------------------------------
Michael Hearne
mhearne@usgs.gov
(303) 273-8620
USGS National Earthquake Information Center
1711 Illinois St. Golden CO 80401
Senior Software Engineer
Synergetics, Inc.
------------------------------------------------------


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/scipy-user/attachments/20080408/ae6e713e/attachment-0001.html 


More information about the SciPy-user mailing list