Created
December 29, 2011 05:49
-
-
Save mactkg/1532207 to your computer and use it in GitHub Desktop.
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
#イテレータの実装 | |
class Fib: | |
'''iterator that yields numbers in the Fibonacci sequence''' | |
def __init__(self, max): | |
self.max = max | |
def __iter__(self): | |
self.a = 0 | |
self.b = 1 | |
return self | |
def __next__(self): | |
fib = self.a | |
if fib > self.max: | |
raise StopIteration | |
self.a, self.b = self.b, self.a + self.b | |
return fib |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
説明
イテレータオブジェクトはdef(関数)ではなくclassで定義する。
クラスの初期化に必要なinitにくわえて、イテレータオブジェクトにはnextとiterが必要になっている。
これは「プロトコル」と言われPythonの中できまりとなっている。この「イテレータプロトコル」を守って実装されたクラスは「イテレータ」と認識される。
(ちなみに、そのプロトコルは最近できたもので、こういった仕様とかもユーザーがどんどん提案している。仕様→http://www.python.org/dev/peps/pep-0234/)
iterメソッドはiter(obj)された時に動いて、nextメソッドはnext(obj)されたときにうごく。
あれ、、、イテレータって何が嬉しいんだっけ…!
参考文献
http://diveintopython3-ja.rdy.jp/iterators.html