[Tutor] 'slice', etc

eryksun eryksun at gmail.com
Sat Dec 7 12:43:12 CET 2013


On Sat, Dec 7, 2013 at 5:42 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>
> Python calls the special dunder method __getindex__ with a as argument.
> If you use a colon inside the square brackets, such as these examples:

__getitem__, but there's an __index __ method that can be useful in
__getitem__. Call it as operator.index().

> Slices go back to the earliest days of Python, although slice objects
> may be newer. In the early days, instead of having a single method
> __getitem__ which sometimes got a slice argument, there was two methods:
>
>     obj[a] => obj.__getitem__(a)
>     obj[a:b] => obj.__getslice__(a, b)
>     obj[a:b:c] => obj.__getslice__(a, b, c)

There's no such thing as __getslice__(a, b, c). In CPython, the
deprecated __getslice__ method (only use this if you have to override
list.__getslice__, etc)  maps to the C function sq_slice(), which
takes an object and exactly two signed size_t integers. The
interpreter uses 0 and sys.maxint as default values if you omit an
index in the slice. It also tries __index__ for a non-integer index.
Otherwise a slice object is created to call __getitem__.


More information about the Tutor mailing list