티스토리 뷰
# 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
"""
'Series' 카테고리의 다른 글
Generator [Python] infinite_generator(), yield, next() (0) | 2018.06.16 |
---|---|
Generator [Python] my_generator(), yield (0) | 2018.06.16 |
Iterator [Python] __iter__(), __next__() (0) | 2018.06.16 |
Iterator [Python] iter(), next() (0) | 2018.06.16 |
Iterable [Python] isinstance(var_list, collections.Iterable) (0) | 2018.06.16 |