Set up Python slicing, please report

I have a class that subclasses a list object. Now I need to process the slicing. Of all that I read on the tubes, this needs to be done using the __getitem__ method. At least in Python 2.7+ this is what I use. I did this (see below), but the __getitem__ method __getitem__ not called when I pass the fragment. Instead, a slice is performed and the list is returned. I would like a new instance of myList to return.

Please help me find out what is wrong.

Thanks!

 class myList(list): def __init__(self, items): super(myList, self).__init__(items) self.name = 'myList' def __getitem__(self, index): print("__getitem__") if isinstance(index, slice): print("slice") return self.__class__( self[x] for x in range(*index.indices(len(self))) ) else: return super(myList, self).__getitem__(index) if __name__ == "__main__": print("\nI'm tesing out custom slicing.\n") N = 10 L = myList(range(N)) L3 = L[3] L02 = L[:2] 
+7
source share
1 answer

See this note :

object.__getslice__(self, i, j)

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

So, because you are a subclass of list , you need to overwrite __getslice__ , although it is deprecated.

I think you should generally avoid subclassing inline functions, too many weird details. If you just want a class that behaves like a list, there is an ABC to help with this:

 from collections import Sequence class MyList(Sequence): def __init__(self, *items): self.data = list(items) def __len__(self): return len(self.data) def __getitem__(self, slice): return self.data[slice] s = MyList(1,2,3) # lots of free methods print s[1:2], len(s), bool(s), s.count(3), s.index(2), iter(s) 
+17
source

All Articles