1.迭代器程序(实现菲比那次数列并且可以抛出与接收异常)
def fib(max):
n,a,b = 0,0,1
while n < max:
#print(b)
yield b
a,b = b,a+b
n= n+1
return 'done'
g = fib(10)
while True:
try:
x = g.__next__()
print('g:',x)
except StopIteration as e:
print('Generator return value:',e.value)
break
2.利用迭代器实现简单的“单线程并行”吃包子(实际上还是串行)
import time
def consumer(name):
print('[%s] prepare to eat baozi!!'%name)
while True:
baozi = yield
print('baozi [%s] is coming,ate by [%s]'%(baozi,name)) def producer(name):
c = consumer('A')
c2 = consumer('B')
c.__next__()
c2.__next__()
print('start'.center(30,'-'))
for i in range(10):
time.sleep(1)
print('just one,half to half')
c.send(i)
c2.send(i) producer('wt')