iteratorを試す
from random import randint class MyRand : def __init__(self, _max) : self.max = max(_max, 1) def __iter__(self) : # next()メソッドが定義してあればselfを返すだけで良いみたい return self def next(self) : r = randint(0, self.max) if r == 0 : raise StopIteration return r
for文はiteratorを回してStopIterationが投げられるまで繰り返す
>>> hoge = MyRand(10) >>> for i in hoge : ... print i ... 8 1 1 1 10 8 1 6 9 >>> iter(a) <test_rand.MyRand instance at 0x7ff3274c> >>> hoge.next() 2 >>> hoge.next() 4 >>> hoge.next() 7 >>> hoge.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "****.py", line 11, in next raise StopIteration StopIteration
0.773 sec

