yield实现状态保存
import time def func(): print(123) sum = 0 print(6666) yield sum print(7777) yield sum print(8888) yield sum def fff(): g = func() print('这是在ffff函数中') print(next(g)) time.sleep(1) print('这是在ffff函数中') print(next(g)) time.sleep(1) print('这是在ffff函数中') print(next(g)) fff() # g = func() #此时不会执行func函数,必须遇到下面代码中的next(g)才会执行函数,并且每一个next(g)只循环一次后,程序将停在while 1:之前,等待下一次next(g) # print('abc') # time.sleep(10) # print(next(g)) # time.sleep(10) # fff() #在fff函数中使用next(g)使得程序fff()和func()交替执行 # time.sleep(10) # print(next(g))