标签:color 中断 orm strong process style roc 方式 ini
生成器
一、yield运行方式
我们定义一个如下的生成器:
def put_on(name):
print("Hi {}, 货物来了,准备搬到仓库!".format(name))
while True:
goods = yield
print("货物[%s]已经被%s搬进仓库了。"%(goods,name))
p = put_on("bigberg")
#输出
G:\python\install\python.exe G:/python/untitled/study4/test/double.py
Process finished with exit code 0
当我们把一个函数通过yield转换成生成器,直接运行函数是不会出现结果返回的。因为此时函数已经是个生成器了,我们要通过next()来取得值,并且在遇到yield时再次跳出函数。
print(type(p)) #输出 <class ‘generator‘>
我们添加next()方法:
def put_on(name):
print("Hi {}, 货物来了,准备搬到仓库!".format(name))
while True:
goods = yield #遇到yield中断
print("货物[%s]已经被%s搬进仓库了。"%(goods,name))
p = put_on("bigberg")
p.__next__()
#输出
Hi bigberg, 货物来了,准备搬到仓库!
此时函数中断在 goods = yield 的地方,当我们再次调用next()函数时,函数只会运行中断以后的内容,即上例中的红色字体部分。
我们再添加一个next():
def put_on(name):
print("Hi {}, 货物来了,准备搬到仓库!".format(name))
while True:
goods = yield
print("货物[%s]已经被%s搬进仓库了。"%(goods,name))
p = put_on("bigberg")
p.__next__()
p.__next__()
#输出
Hi bigberg, 货物来了,准备搬到仓库!
货物[None]已经被bigberg搬进仓库了。
我们可以看到yield并没有给goods传值,所有货物是 None。
小结:
二、send()传值
def put_on(name):
print("Hi {}, 货物来了,准备搬到仓库!".format(name))
while True:
goods = yield
print("货物[%s]已经被%s搬进仓库了。"%(goods,name))
p = put_on("bigberg")
p.__next__()
p.send("瓜子")
#输出
Hi bigberg, 货物来了,准备搬到仓库!
货物[瓜子]已经被bigberg搬进仓库了。
小结:
def put_on(name):
print("Hi {}, 货物来了,准备搬到仓库!".format(name))
while True:
goods = yield
print("货物[%s]已经被%s搬进仓库了。"%(goods,name))
p = put_on("bigberg")
p.__next__()
p.send("瓜子")
p.send("花生")
p.send("饼干")
p.send("牛奶")
#多次调用send()
Hi bigberg, 货物来了,准备搬到仓库!
货物[瓜子]已经被bigberg搬进仓库了。
货物[花生]已经被bigberg搬进仓库了。
货物[饼干]已经被bigberg搬进仓库了。
货物[牛奶]已经被bigberg搬进仓库了。
三、单线程实现并行效果(协程)
import time
def put_on(name):
print("Hi {}, 货物来了,准备搬到仓库!".format(name))
while True:
goods = yield
print("货物[%s]已经被%s搬进仓库了。"%(goods,name))
def transfer(name):
p = put_on(‘A‘)
p2 = put_on(‘B‘)
p.__next__()
p2.__next__()
print("%s将货物送来了!"%name)
for i in range(5):
time.sleep(1)
print("%s递过来两件货物"%name)
p.send("瓜子")
p2.send("花生")
transfer("bigberg")
#输出
Hi A, 货物来了,准备搬到仓库!
Hi B, 货物来了,准备搬到仓库!
bigberg将货物送来了!
bigberg递过来两件货物
货物[瓜子]已经被A搬进仓库了。
货物[花生]已经被B搬进仓库了。
bigberg递过来两件货物
货物[瓜子]已经被A搬进仓库了。
货物[花生]已经被B搬进仓库了。
bigberg递过来两件货物
货物[瓜子]已经被A搬进仓库了。
货物[花生]已经被B搬进仓库了。
bigberg递过来两件货物
货物[瓜子]已经被A搬进仓库了。
货物[花生]已经被B搬进仓库了。
bigberg递过来两件货物
货物[瓜子]已经被A搬进仓库了。
货物[花生]已经被B搬进仓库了。
标签:color 中断 orm strong process style roc 方式 ini
原文地址:http://www.cnblogs.com/bigberg/p/6714598.html