I make a class like below:
class MyList(list):
def __init__(self, lst):
self.list = lst
I want slice functionality to be overridden in MyList
You need to provide custom __getitem__(), __setitem__ and __delitem__ hooks.
These are passed a slice object when slicing the list; these have start, stop and step attributes (which could be None):
def __getitem__(self, key):
if isinstance(key, slice):
return [self.list[i] for i in xrange(key.start, key.stop, key.step)]
return self.list[key]
or, for your case:
def __getitem__(self, key):
return self.list[key]
because a list can take the slice object directly.
In Python 2, list.__getslice__ is called for slices without a stride (so only start and stop indices) if implemented, and the built-in list type implements it so you'd have to override that too; a simple delegation to your __getitem__ method should do fine:
def __getslice__(self, i, j):
return self.__getitem__(slice(i, j))
class MyList(list):
def __init__(self, lst):
self.list = lst
doesn't make much sense... self is the list object itself, and it has already been created at this point, maybe you want to override __new__, however you probably don't need to touch that. Anyway you want to override __getitem__ like so:
def __getitem__(self, val):
if isinstance( val, slice):
# do stuff here
来源:https://stackoverflow.com/questions/16033017/how-to-override-the-slice-functionality-of-list-in-its-derived-class