这个问题被多次询问,但我没有直接看到我的版本的答案,所以......
使用迭代器协议,如下面的例子,我可以创建像迭代器一样的对象,也像生成器一样。
示例:
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)