且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当切片索引超出范围时,如何引发IndexError?

更新时间:2021-11-08 22:50:06

在Python 2中,您可以通过这种方式覆盖 __ getslice __ 方法:

In Python 2 you can override __getslice__ method by this way:

class MyList(list):
    def __getslice__(self, i, j):
        len_ = len(self)
        if i > len_ or j > len_:
            raise IndexError('list index out of range')
        return super(MyList, self).__getslice__(i, j)

然后使用您的班级而不是列表

Then use your class instead of list:

>>> egg = [1, "foo", list()]
>>> egg = MyList(egg)
>>> egg[5:10]
Traceback (most recent call last):
IndexError: list index out of range