Passing Python slice syntax around to functions

前端 未结 3 821
青春惊慌失措
青春惊慌失措 2020-12-16 12:18

In Python, is it possible to encapsulate exactly the common slice syntax and pass it around? I know that I can use slice or __slice__ to emulate sl

3条回答
  •  心在旅途
    2020-12-16 13:09

    Perhaps something along the following lines would work for you:

    class SliceMaker(object):
      def __getitem__(self, item):
        return item
    
    make_slice = SliceMaker()
    
    print make_slice[3]
    print make_slice[0:]
    print make_slice[:-1]
    print make_slice[1:10:2,...]
    

    The idea is that you use make_slice[] instead of manually creating instances of slice. By doing this you'll be able to use the familiar square brackets syntax in all its glory.

提交回复
热议问题