Python:如何从列表[-1]中获取错误?

时间:2015-09-30 15:49:33

标签: python python-3.x

有没有办法为索引值[-1]返回错误?

>>>l=[1,2,3]
>>>l[-1]
error:list index out of range

1 个答案:

答案 0 :(得分:2)

不适用于内置列表类型,但您可以定义自己的具有更严格索引规则的类:

>>> class StrictList(list):
...     def __getitem__(self, index):
...             if index < 0:
...                     raise IndexError("negative integers are forbidden")
...             return list.__getitem__(self, index)
...
>>> seq = StrictList([1,2,3])
>>> seq[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __getitem__
IndexError: 'negative integers are forbidden'