【发布时间】:2016-12-16 18:19:28
【问题描述】:
为什么函数生成器和类生成器的行为不同?我的意思是,对于类生成器,我可以根据需要多次使用生成器,但是对于函数生成器,我只能使用一次吗?为什么会这样?
def f_counter(low,high):
counter=low
while counter<=high:
yield counter
counter+=1
class CCounter(object):
def __init__(self, low, high):
self.low = low
self.high = high
def __iter__(self):
counter = self.low
while self.high >= counter:
yield counter
counter += 1
f_gen=f_counter(5,10)
for i in f_gen:
print(i,end=' ')
print('\n')
for j in f_gen:
print(j,end=' ') #no output
print('\n')
c_gen=CCounter(5,10)
for i in c_gen:
print(i,end=' ')
print('\n')
for j in c_gen:
print(j,end=' ')
【问题讨论】:
标签: python python-3.x generator