实例讲解Python中的yield协程
1、打开Python开发工具IDLE,新建‘yieldpro.py’,并写代码如下;def testcoroutine(): print ('start') c = yield print ('over')print (testcoroutine())

3、next触发生成器函数执行(也可以用 send(None)),当yield右侧没有值时,返回Nonedef testcoroutine(): print (&垆杪屑丝#39;start') c = yield print ('over')print (testcoroutine())mycor = testcoroutine()print (next(mycor))

5、给yield左侧赋值要用send,代码如下;def testcoroutine(): print ('start') c = yield print (c) print ('over')print (testcoroutine())mycor = testcoroutine()print (next(mycor))mycor.send(2)

7、生成器还有close方法,当调用了close方法再用next或send就会抛出异常。def testcoroutine(): print ('start') c = yield d = yield print (c) print ('over')print (testcoroutine())mycor = testcoroutine()print (next(mycor))mycor.close()print (next(mycor))
8、F5运行程序,抛出异常,如果注释掉close()方法,就不会
