Skip to content

Instantly share code, notes, and snippets.

@mactkg
Created December 29, 2011 05:21
Show Gist options
  • Save mactkg/1532091 to your computer and use it in GitHub Desktop.
Save mactkg/1532091 to your computer and use it in GitHub Desktop.
generator
def make_counter(x):
print('entering make_counter')
while True:
yield x
x = x + 1
counter = make_counter(0)
counter #=> <generator object at *pointer*>
next(counter) #=> 0
next(counter) #=> 1
next(counter) #=> 2
@mactkg
Copy link
Author

mactkg commented Dec 29, 2011

説明

普通に関数を定義しreturnの変わりにyieldを使うと、ジェネレータオブジェクトとなる。
ジェネレータオブジェクトのインスタンスを作るためには、他のクラスみたいにやれば良い。
yieldはそこで値を返すものの、関数が終わらない限りオブジェクトの中身は保存されている(xの値とか)。
次の値が欲しければnext(obj)とすれば値を得られる。
whileを抜けるとどうなるかは、次を見てください

参考文献

http://diveintopython3-ja.rdy.jp/generators.html#ジェネレータ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment