This question was asked many times, but I didn't see an answer for my version directly, so...
With iterator protocol, like example below I could make objects that behave like iterators and also like generators.
- Is there real distinction between an iterator and a generator on object level?
- Is yield keyword just a sugar to python interpreter to create class with iterator protocol?
- Could I replace every generator (or co-routine) function with a class that supports iterator protocol?
Examples:
def make_iterable():
return [1, 2, 3, 4, 5]
# This class behaves like a function above when iterating its instances.
class IteratorBehave(object):
def __init__(self):
self.data = [1, 2, 3, 4, 5]
def __iter__(self):
class Iter(object):
def __init__(self, data):
self.index = 0
self.data = data
def next():
if self.index < len(self.data):
current = self.data[self.index]
self.index += 1
return current
raise StopIteration()
return Iter(self.data)
def make_generator():
v = 1
while v <= 5:
yield v
v += 1
# This class behaves like a generator function above when iterating its instances.
class GeneratorBehave(object):
def __init__(self):
self.max = 5
def __iter__(self):
class Gen(object):
def __init__(self, max):
self.current = 1
self.max = max
def next():
if self.current <= self.max:
current = self.current
self.current += 1
return current
raise StopIteration()
return Gen(self.max)