How does a list slice a hook into __getitem__?

>>> class List(list):
...     def __getitem__(self, i):
...         print i, type(i)
...         return super(List, self).__getitem__(i)
...     
>>> x = List([0,1,2,3])
>>> x[1:3:]
slice(1, 3, None) <type 'slice'>
[1, 2]
>>> x[1:3]
[1, 2]

Why is the second case not using List.__getitem__? What does he use instead?

>>> x[::]
slice(None, None, None) <type 'slice'>
[0, 1, 2, 3]
>>> x[:]
[0, 1, 2, 3]

Repeat the same thing, why the discrepancy here is not these two slicing operations?

+4
source share
2 answers

the link to the language says it all. In particular:

  

Deprecated since version 2.0: support for slice objects as parameters __getitem__(). (However, the built-in types in CPython still implement __getslice__(). Therefore, you must override it in derived classes when implementing slicing. )

  

and

  

self [i: j]...

  

, self[i:j:]...

+2

python2.7, , :

k , <= k < j, j - .

0

All Articles