What are the default slice indices in Python *really*?

后端 未结 6 1725
死守一世寂寞
死守一世寂寞 2020-11-30 11:53

From the python documentation docs.python.org/tutorial/introduction.html#strings:

Slice indices have useful defaults; an omitted first index defaults

6条回答
  •  忘掉有多难
    2020-11-30 12:20

    Useful to know if you are implementing __getslice__: j defaults to sys.maxsize (https://docs.python.org/2/reference/datamodel.html#object.getslice)

    >>> class x(str):
    ...   def __getslice__(self, i, j):
    ...     print i
    ...     print j
    ...
    ...   def __getitem__(self, key):
    ...     print repr(key)
    ...
    >>> x()[:]
    0
    9223372036854775807
    >>> x()[::]
    slice(None, None, None)
    >>> x()[::1]
    slice(None, None, 1)
    >>> x()[:1:]
    slice(None, 1, None)
    >>> import sys
    >>> sys.maxsize
    9223372036854775807L
    

提交回复
热议问题