Method(s) called by square brackets, slice objects

Steven D'Aprano steve at pearwood.info
Wed Apr 9 22:52:26 EDT 2014


On Wed, 09 Apr 2014 13:24:32 -0700, John Ladasky wrote:

> I would like to build a multi-dimensional array that allows numpy-style
> indexing and, ideally, uses Python's familiar square-bracket and slice
> notations.
> 
> For example, if I declare a two-dimensional array object, x, then x[4,7]
> retrieves the element located at the 4th row and the 7th column.  If I
> ask for x[3:6,1:3], I get a 3 x 2 array object consisting of the
> intersection of the 3rd-5th rows, and the 1st-2nd columns, of x.
> 
> In this case I'm not allowed to use numpy, I have to restrict myself to
> the standard library.  I thought that I might achieve the desired
> behavior by defining an object with specific __getitem__ and/or
> __getslice__ methods.  

Use __getitem__, __getslice__ is deprecated in Python 2 and gone in 
Python 3.

https://docs.python.org/2/reference/datamodel.html#object.__getslice__


> However, the documentation of these methods that
> I am reading suggests that the arguments are pre-parsed into certain
> formats which may not allow me to do things numpy's way.  Is this true?

Why don't you try it in the interactive interpreter and see?


py> class Test(object):
...     def __getitem__(self, thing):
...             print thing
... 
py> obj = Test()
py> obj[1]
1
py> obj[1:2]
slice(1, 2, None)
py> obj[1:2:3]
slice(1, 2, 3)
py> obj[1,5:2:3]
(1, slice(5, 2, 3))
py> obj[1:2:3,4:5:6]
(slice(1, 2, 3), slice(4, 5, 6))
py> obj[1,2,3]
(1, 2, 3)
py> obj[1,2,"spam"]
(1, 2, 'spam')
py> obj[1,2,"spam":"eggs",3]
(1, 2, slice('spam', 'eggs', None), 3)




-- 
Steven



More information about the Python-list mailing list