AdityaSriram

Python Subclassing list

Nov 27th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.21 KB | None | 0 0
  1. class Mylist(list):
  2.  
  3.     def __getitem__(self, item):
  4.         print "mygetitem called with", item
  5.         # check if item is slice (l[a:b:c]) or not (l[a])
  6.         if isinstance(item, slice):  # item is slice, check if negative start or stop
  7.             if item.start < 0 or item.stop < 0:
  8.                 raise ValueError("negative indexing not supported")
  9.             else:
  10.                 return list.__getitem__(self, item)
  11.         else:  # item is single index, check if its negative
  12.             if item < 0:
  13.                 raise ValueError("negative indexing not supported")
  14.             else:
  15.                 return list.__getitem__(self, item)
  16.  
  17.     # it seems for getslice, python automatically adjusts start and stop values
  18.     # if they are negative it adds len to it that way we don't receive negative values
  19.     # when called like l[0:-1], we receive l[0:len(l)-1]
  20.     def __getslice__(self, start, stop):
  21.         print "mygetslice called with", start, stop
  22.         return list.__getslice__(self, start, stop)
  23.    
  24.    
  25. l = Mylist((1,2,3)) # or l = Mylist(range(10))
  26. print l[0]
  27. print l[5]
  28. print l[-1] # error
  29. print l[0:5]
  30. print l[0:-1] # no error in Python2
  31. print l[0:5:1]
  32. print l[0:-1:1] # error
Add Comment
Please, Sign In to add comment