Series
Iterator [Python] class CountDown, __iter__(), __next__()
More Code
2018. 6. 16. 09:49
# Python 3 : Iterator
class CountDown:
def __init__(self, top: int):
self.current = top + 1
def __iter__(self) -> 'CountDown':
return self
def __next__(self) -> int:
self.current -= 1
if self.current < 0:
raise StopIteration
else:
return self.current
if __name__ == '__main__':
c1 = CountDown(3)
print(type(c1)) # <class '__main__.CountDown'>
for i in c1:
print(i) # 3 2 1 0
c2 = CountDown(3)
print(next(c2)) # 3
print(next(c2)) # 2
print(next(c2)) # 1
print(next(c2)) # 0
print(next(c2)) # StopIteration
""" Output
3
2
1
0
3
2
1
0
StopIteration
"""