通常の関数と異なり、前回返した値を覚えているようです。
呼び出すと次の値を返します。
generator.py
def counter(num=10):
for _ in range(num):
yield 'run'
def greeting():
yield 'good morning'
yield 'good afternoon'
yield 'good night'
for g in greeting():
print(g)
g=greeting()
print(next(g)) #good morning
print(next(g)) #good afternoon
c=counter()
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
#print(next(c)) エラー出る
出力:
good morning
good afternoon
good night
good morning
good afternoon
run
run
run
run
run
run
run
run
run
run