I have a class that subclasses the list object. Now I need to handle slicing. From everything I read on the intertubes this has to be done using the __getitem__
method. At least in Python 2.7+ which is what I'm using. I have done this (see below), but the __getitem__
method isn't called when I pass in a slice. Instead, a slice is done and a list is returned. I would like a new instance of myList returned.
Please help me discover 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]
See this note:
So, because you subclass
list
you have to overwrite__getslice__
, even though it's deprecated.I think you should generally avoid subclassing builtins, there are too many weird details. If you just want a class that behaves like a list, there is a ABC to help with that: