Skip to content

Instantly share code, notes, and snippets.

@mactkg
Created December 29, 2011 05:49
Show Gist options
  • Save mactkg/1532207 to your computer and use it in GitHub Desktop.
Save mactkg/1532207 to your computer and use it in GitHub Desktop.
#イテレータの実装
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
@mactkg
Copy link
Author

mactkg commented Dec 29, 2011

説明

イテレータオブジェクトはdef(関数)ではなくclassで定義する。
クラスの初期化に必要なinitにくわえて、イテレータオブジェクトにはnextiterが必要になっている。
これは「プロトコル」と言われPythonの中できまりとなっている。この「イテレータプロトコル」を守って実装されたクラスは「イテレータ」と認識される。
(ちなみに、そのプロトコルは最近できたもので、こういった仕様とかもユーザーがどんどん提案している。仕様→http://www.python.org/dev/peps/pep-0234/)
iterメソッドはiter(obj)された時に動いて、nextメソッドはnext(obj)されたときにうごく。
あれ、、、イテレータって何が嬉しいんだっけ…!

参考文献

http://diveintopython3-ja.rdy.jp/iterators.html

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