Example Code:
Iterables in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# Author: Huahua class MyListIterator: def __init__(self, my_list, index=0): self.my_list = my_list self.index = index def __next__(self): if self.index < len(self.my_list.data): val = self.my_list.data[self.index] self.index += 1 return val else: raise StopIteration() def __iter__(self): return MyListIterator(self.my_list, self.index) # return self class MyList: def __init__(self, data): self.data = list(data) def __getitem__(self, index): return self.data[index] def __len__(self): return len(self.data) def __iter__(self): return MyListIterator(self) my_list = MyList([1,2,3,4,5]) it = iter(my_list) next(it) it2 = iter(it) next(it) print('--- it ---') for x in it: print(x) # 3, 4, 5 print('--- it2 ---') for x in it2: print(x) # 2, 3, 4, 5 |