[SciPy-user] overriding __getitem__

Michael Hearne mhearne at usgs.gov
Tue Apr 8 12:22:36 EDT 2008


In numpy, it is possible to use the square bracket operators [] in  
various ways:

x = numpy.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
x[0,0]
x[0:2,0:2]
x[0:4:2,0:4:2]

I presume that under the hood, the numpy array object is overriding  
the __getitem__ method.

Based on that assumption, I created the following test code that I  
_thought_ should work:
------------------------------------------------------------------------ 
--------------------
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?

Thanks,

Mike



------------------------------------------------------
Michael Hearne
mhearne at 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://mail.scipy.org/pipermail/scipy-user/attachments/20080408/d352454e/attachment.html>


More information about the SciPy-User mailing list