Redefining python list
is it 开发者_如何学编程possible to redefine the behavior of a Python List from Python, I mean, without having to write anything in the Python sourcecode?
You could always create your own subclass inheriting from list.
An example (although you would probably never want to use this):
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
精彩评论