如何阻止Python列表中的负索引?

问题描述 投票:0回答:1

我正在尝试用 Python 制作一个基本的元胞自动机,但是我的列表边界出现了问题。由于索引超过长度,我用 try except 结构解决了它,但我不知道我是否可以用基本列表类来做我想做的事情。

我不介意创建一个类,但我不知道我是否应该创建一个完全下一个类或只是从列表继承。即使这样我也不知道要从类列表中修改什么

python
1个回答
0
投票

您需要创建一个

class
,并重写其
__getitem__
方法。 这是代码:

class CustomizedList(list):
    def __getitem__(self, index):
        if index < 0:
            raise IndexError("Negative indices are not allowed")
        elif index > len(self):
            raise IndexError("Index out of Range")
        return super().__getitem__(index)

my_list = CustomizedList([1, 2, 3, 4, 5])

# print(my_list[6])  # Index out of Range
try:
    print(my_list[-1])
except Exception as e:
    print(e)

现在,每当有人尝试使用负索引或大于长度的索引时,都会相应地引发

exception

© www.soinside.com 2019 - 2024. All rights reserved.