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
| class Stack: def __init__(self,*args): self.__items = list(args) self.__index = 0
def __iter__(self): return self
def __next__(self): if self.__index < len(self.__items): item = self.__items[self.__index] self.__index += 1 return item else: raise StopIteration
s = Stack(1,2,3,4) for item in s: print(item)
iterator = iter(s) print(next(iter(iterator))) print(next(iter(iterator))) print(next(iter(iterator))) print(next(iter(iterator))) print(next(iter(iterator)))
|