对于普通的生成器,第一个next调用,相当于启动生成器,会从生成器函数的第一行代码开始执行,直到第一次执行完yield语句(第4行)后,跳出生成器函数。
然后第二个next调用,进入生成器函数后,从yield语句的下一句语句(第5行)开始执行,然后重新运行到yield语句,执行后,跳出生成器函数,
后面再次调用next,依次类推。下面是一个例子:
def consumer(): r = 'here' for i in range(3): yield r r = '200 OK'+ str(i) c = consumer() n1 = c.__next__() n2 = c.__next__() n3 = c.__next__() print(n1) print(n2) print(n3) 打印结果如下: here 200 OK0 200 OK1