What does the slice() function do in Python?

后端 未结 4 1054
轻奢々
轻奢々 2020-12-02 18:52

First of all, I\'d like to clarify the question: it\'s about the slice() function, not slices of lists or strings like a[5:4:3].

The docs menti

4条回答
  •  没有蜡笔的小新
    2020-12-02 19:06

    No, it's not all!

    As objects are already mentioned, first you have to know is that slice is a class, not a function returning an object.

    Second use of the slice() instance is for passing arguments to getitem() and getslice() methods when you're making your own object that behaves like a string, list, and other objects supporting slicing.

    When you do:

    print "blahblah"[3:5]
    

    That automatically translates to:

    print "blahblah".__getitem__(slice(3, 5, None))
    

    So when you program your own indexing and slicing object:

    class example:
        def __getitem__ (self, item):
            if isinstance(item, slice):
                print "You are slicing me!"
                print "From", item.start, "to", item.stop, "with step", item.step
                return self
            if isinstance(item, tuple):
                print "You are multi-slicing me!"
                for x, y in enumerate(item):
                    print "Slice #", x
                    self[y]
                return self
            print "You are indexing me!\nIndex:", repr(item)
            return self
    

    Try it:

    >>> example()[9:20]
    >>> example()[2:3,9:19:2]
    >>> example()[50]
    >>> example()["String index i.e. the key!"]
    >>> # You may wish to create an object that can be sliced with strings:
    >>> example()["start of slice":"end of slice"]
    

    Older Python versions supported the method getslice() that would be used instead of getitem(). It is a good practice to check in the getitem() whether we got a slice, and if we did, redirect it to getslice() method. This way you will have complete backward compatibility.

    This is how numpy uses slice() object for matrix manipulations, and it is obvious that it is constantly used everywhere indirectly.

提交回复
热议问题