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
您总是可以创建自己的继承自列表的子类。在
一个例子(虽然你可能永远都不想用这个):
相关问题 更多 >
编程相关推荐