changing the List's behaviour?
Peter Otten
__peter__ at web.de
Mon Jul 28 08:46:14 EDT 2003
meinrad recheis wrote:
> i want to change the List so that it returns None if the index for
> accesssing list elements
> is out of bound.
If you really need it, you can write a class similar to the one below:
class DefaultList(list):
def __init__(self, sequence=[], default=None):
list.__init__(self, sequence)
self.default = default
def __getitem__(self, index):
try:
return list.__getitem__(self, index)
except IndexError:
return self.default
if __name__ == "__main__":
theList = DefaultList("abc", "?")
print theList[1]
print theList[99]
theList = DefaultList(default="X")
print theList[1]
More information about the Python-list
mailing list