I read something about the slice in Python 3. Then I wrote a program and tried to implement it __getitem__(self, slice(s)). The code goes below:
class NewList:
def __init__(self, lst):
print('new list')
self._list = lst
def __getitem__(self, x):
if type(x) is slice:
return [ self._list[n] for n in range(x.start, x.stop, x.step) ]
else:
return self._list[x]
...
nl1 = NewList([1,2,3,4,5])
nl1[1:3]
Then I found out that it x.stepis equal None, which made the range raise exception. So how do I implement a method __getitem__?
source
share