-1

I have a simple class that takes a List of objects as an input, and I want to ensure I can perform slicing on that operation.

class MyClass(AbstractLocationClass):
    def __init__(locations=None, **kwargs):
       if locations is None:
           locations = []
       self._locations = locations
       #... do other stuff with kwargs..

I want to allow users to do the following:

 m = MyClass(locations=[[1,2],[2,3],[3,4]])
 sliced = m[0:1]
 print sliced 
 >>> [[1,2],[2,3]]

I know I have to override __getitem__ but what I'm unsure of is how to handle all the notation types like obj[0], obj[1:2], etc...

Can someone please advise on the proper way of implementing this feature.

code base 5000
  • 3,812
  • 13
  • 44
  • 73

1 Answers1

2

What I figured out is that I needed to check if the index was of type slice

#----------------------------------------------------------------------
def __getitem__(self, index):
    """slicing"""
    if len(self) == 0:
        return []

    if isinstance(index, slice):
        return self._locations[index]
    else:
        if index <= len(self) -1:
            return self._locatios[index]
        else:
            raise ValueError("Invalid index")
code base 5000
  • 3,812
  • 13
  • 44
  • 73