Programming/Python/iterator

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

Search

Blog

Twitter

Wassr

Recommend


とりあえず買っとく?

Ads

ドミノ・ピザ 5%OFF!

 iTunes Store(Japan)

KINOWIKI

Total: 77

Today: 1

Yesterday: 2

edit

Counter

total : 00059980
today : 00000041