Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #69983

Re: Method(s) called by square brackets, slice objects

Date 2014-04-09 13:34 -0700
From Ethan Furman <ethan@stoneleaf.us>
Subject Re: Method(s) called by square brackets, slice objects
References <74d6fb5c-baca-4606-9fa8-66238a561e0c@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.9096.1397077000.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 04/09/2014 01:24 PM, 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 inter-
>section 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.
> 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?

Nope.  Whatever you put between the square brackets is what gets passed into __getitem__; the only caveat is that 
anything with : will be turned into a slice:

Python 2.7.3 (default, Sep 26 2012, 21:51:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
--> class GetIndex(object):
...   def __getitem__(self, thing):
...     print thing
...     return None
...
--> test = GetIndex()

--> test[1]
1

--> test [1,2]
(1, 2)

--> test[1:3, 4:5]
(slice(1, 3, None), slice(4, 5, None))

--> test[range(3)]
[0, 1, 2]

--
~Ethan~

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Method(s) called by square brackets, slice objects John Ladasky <john_ladasky@sbcglobal.net> - 2014-04-09 13:24 -0700
  Re: Method(s) called by square brackets, slice objects Ethan Furman <ethan@stoneleaf.us> - 2014-04-09 13:34 -0700
  Re: Method(s) called by square brackets, slice objects Steven D'Aprano <steve@pearwood.info> - 2014-04-10 02:52 +0000
  Re: Method(s) called by square brackets, slice objects John Ladasky <john_ladasky@sbcglobal.net> - 2014-04-10 11:52 -0700
    Re: Method(s) called by square brackets, slice objects Terry Reedy <tjreedy@udel.edu> - 2014-04-10 18:20 -0400

csiph-web