Created
December 29, 2011 05:21
-
-
Save mactkg/1532091 to your computer and use it in GitHub Desktop.
generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
説明
普通に関数を定義しreturnの変わりにyieldを使うと、ジェネレータオブジェクトとなる。
ジェネレータオブジェクトのインスタンスを作るためには、他のクラスみたいにやれば良い。
yieldはそこで値を返すものの、関数が終わらない限りオブジェクトの中身は保存されている(xの値とか)。
次の値が欲しければnext(obj)とすれば値を得られる。
whileを抜けるとどうなるかは、次を見てください
参考文献
http://diveintopython3-ja.rdy.jp/generators.html#ジェネレータ