This is a class that produces iterable objects:
class gen( object): def __init__( self, n): self.n_total = n self.n = 0 def __iter__( self): return self def next( self): if self.n < self.n_total: temp = self.n self.n += 1 return temp else: raise StopIteration() g = gen(10) print( [n for n in g]) # # prints [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] #
The same can be achieved with a generator function:
def gen(n): i = 0 while i < n: yield i i += 1 for i in gen(10): print( i)