Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Mylist(list):
- def __getitem__(self, item):
- print "mygetitem called with", item
- # check if item is slice (l[a:b:c]) or not (l[a])
- if isinstance(item, slice): # item is slice, check if negative start or stop
- if item.start < 0 or item.stop < 0:
- raise ValueError("negative indexing not supported")
- else:
- return list.__getitem__(self, item)
- else: # item is single index, check if its negative
- if item < 0:
- raise ValueError("negative indexing not supported")
- else:
- return list.__getitem__(self, item)
- # it seems for getslice, python automatically adjusts start and stop values
- # if they are negative it adds len to it that way we don't receive negative values
- # when called like l[0:-1], we receive l[0:len(l)-1]
- def __getslice__(self, start, stop):
- print "mygetslice called with", start, stop
- return list.__getslice__(self, start, stop)
- l = Mylist((1,2,3)) # or l = Mylist(range(10))
- print l[0]
- print l[5]
- print l[-1] # error
- print l[0:5]
- print l[0:-1] # no error in Python2
- print l[0:5:1]
- print l[0:-1:1] # error
Add Comment
Please, Sign In to add comment