In Py2.3, __getitem__ conveniently supports slices for builtin sequences: 'abcde'.__getitem__(slice(2,4)) For user defined classes to emulate this behavior, they need to test the index argument to see whether it is a slice and then loop over the slice indices like this: class SquaresToTen: """Acts like a list of squares but computes only when needed""" def __len__(self): return 11 def __getitem__(self, index): if isinstance(index, slice): return [x**2 for x in range(index.start, index.stop, index.step)] else: return index**2 print SquaresToTen()[2] print SquaresToTen()[7:1:-2] This could be simplified somewhat by making slices iterable so that the __getitem__ definition looks more like this: def __getitem__(self, index): if isinstance(index, slice): return [x**2 for x in index] else: return index**2 Raymond Hettinger
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4