How to override the slice functionality of list in its derived class

喜夏-厌秋 提交于 2019-11-27 09:02:32

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!