生成器函数每次执行都会从头开始,也就是复位的效果,如果将生成器赋给变量,对变量的操作会继续下去,不会自动复位。如下例所示:
def testGen():
for i in range(100):
yield i
count = 0
for i in testGen():
print(i, end=', ')
count += 1
if count > 3:
break
#输出:0, 1, 2, 3,
count = 0
for i in testGen():
print(i, end=', ')
count += 1
if count > 3:
break
#依然输出:0, 1, 2, 3,
test_gen = testGen()
count = 0
for i in test_gen:
print(i, end=', ')
count += 1
if count > 3:
break
#输出:0, 1, 2, 3,
count = 0
for i in test_gen:
print(i, end=', ')
count += 1
if count > 3:
break
#继续输出:4, 5, 6, 7,