LoginSignup
1
1

More than 3 years have passed since last update.

ジェネレータ

Last updated at Posted at 2020-02-15

通常の関数と異なり、前回返した値を覚えているようです。
呼び出すと次の値を返します。

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
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1