ジェネレータ(2)

前回は無限に続くジェネレータを紹介したが、今回は打ち切るのを。


def count(n):
i = 0
while i < n:
yield i
i += 1

for i in count(3):
print i,


0 1 2

ジェネレータが関数の最後まで行くと、StopIterationという例外を投げる。これは、次のコードで実証される。


def count(n):
i = 0
while i < n:
yield i
i += 1

c = count(3)
while True:
try:
print c.next(),
except StopIteration:
break

例外は、上のように try 〜 except で処理できる。
だから、上のジェネレータと同様のクラスを作ると、次のようになる。


class count:
def __init__(self, n):
self.n = n
self.i = 0

def __iter__(self):
return self

def next(self):
self.i += 1
if self.i > self.n:
raise StopIteration
return self.i - 1

for i in count(3):
print i,

例外は、raise で投げることができる。