Pythonとイテレータ

class Counter:
  def __init__(self, max):
    self.max = max
  def __iter__(self):
    self.n = 0
    return self
  def next(self):
    if self.n > self.max - 1:
      raise StopIteration
    self.n += 1
    return self.n - 1

if __name__ == '__main__':
    for i in Counter(5):
        print(i)

イテレータはfor文に使える。
イテレータは__iter__メソッドと、nextメソッド(python3だと__next__?)を持つこと。StopIteration例外でストップさせる。