重新定义Python列表

0 投票
1 回答
803 浏览
提问于 2025-04-16 05:51

有没有可能在Python中重新定义列表的行为,也就是说,不用修改Python的源代码?

1 个回答

3

你可以自己创建一个类,让它继承自列表(list)。

下面是一个例子(虽然你可能不会真的想用这个):

class new_list(list):
    '''A list that will return -1 for non-existent items.'''
    def __getitem__(self, i):
        if i >= len(self):
            return -1
        else:
            return super(new_list, self).__getitem__(i)

l = new_list([1,2,3])
l[2] #returns 3 just like a normal list
l[3] #returns -1 instead of raising IndexError

撰写回答