This will automaticly return then next integer forever it starts with 0. This is an example of how to make a generator and how to make a callable object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Inc: def __init__(self): self.x=0 self.inc=self.giveone() def giveone(self): while True: yield self.x self.x+=1 def __call__(self): return self.inc.next() inc=Inc() for x in range(10): inc() assert (inc()==10)==True assert (inc()==12)==False
I made this because I was making animated gifs. I wanted to name all the pictures in sequence and this was a nice clean way to generate the next number in the sequence. I did not need to backtrack at all so it seemed like a generator was called for. Also I did not want to call gen.next() in order to get my number.
Easier... You don't benefit from using a class here.
def inc(x=0): while 1: yield x x += 1
is certainly simpler.
This is what I should have used. I obviously should look more closely at itertools.