inside []
in python, the language spec parses :
s into slice objects.
you can either give it just the one :
, or two. If you omit values, then they are treated specially (i.e. as end values).
It's described here
More in-depth:
When parsing a program, []
are treated differently from other parts of the code;
as seen here:
trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
subscriptlist: subscript (',' subscript)* [',']
subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop]
sliceop: ':' [test]
in the python grammar
The bit that's important there is noting that the individual subscript
s can either be ...
or a single item (in this case test
), or optional test
s separated by :
.
The point is though, that when you do use the :
in there, it's translated into a slice object, which is just passed to the __getitem__
object method*.
How your object
deals with the slice objects it gets passed is up to it's implementation of __getitem__
. Try doing something like this:
class my_class(object):
def __getitem__(*slices):
print slices
pass
c = my_class()
c[1]
c[1:2]
c[1:2:3]
c[:2]
c[::3]
c[1::3]
c[1, 1:, :2, ::3, 1:2, 1::3, object(), [1,2,3,4,5]]
Note that all that's happening is that the various objects you put inbetween the []
jsut get passed to the __getitem__
method. The only different between then and any other place in python, is that inside []
there is the additional parsing of the slice()
shortcut syntax start:end:step
.
*at least it is for any object you create. Soem of the builtins do it a little differently - i think for legacy reasons.