迭代器和生成器
ite=iter([1,2,3,4,5])#迭代器
print(ite.next())#1
print(ite.next())#2
print(ite.next())#3
print(ite.next())#4
def cash_money(money):#这个函数是生成器(yield)但返回的结果是一个迭代器
money-=100
yield 100
print('again get money..')
atm=cash_money(500)
print(type(atm))#<type 'generator'>
print(atm.next())
print(atm.next())
print(atm.next())
print('i will go to play..')
print(atm.next())
#ret 正常的函数是需将函数执行完时才做做其它操作,但yield却实现了异步的效果
100
again get money...
100
again get money...
100
i will go to play..
again get money...
100
import
time
def
consumer(name):
print
(
"%s 准备吃包子啦!"
%
name)
while
True
:
baozi
=
yield
print
(
"包子[%s]来了,被[%s]吃了!"
%
(baozi,name))
def
producer(name):
c
=
consumer(
'A'
)
c2
=
consumer(
'B'
)
c.__next__()
c2.__next__()
print
(
"老子开始准备做包子啦!"
)
for
i
in
range
(
10
):
time.sleep(
1
)
print
(
"做了2个包子!"
)
c.send(i)
c2.send(i)
producer(
"alex"
)