重新定义python-lis

2024-04-20 02:54:35 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有可能从Python中重新定义Python列表的行为,而不必在Python源代码中编写任何东西?在


Tags: 列表定义源代码
1条回答
网友
1楼 · 发布于 2024-04-20 02:54:35

您总是可以创建自己的继承自列表的子类。在

一个例子(虽然你可能永远都不想用这个):

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

相关问题 更多 >