实例讲解Python中的yield协程

 时间:2026-02-16 09:24:43

1、打开Python开发工具IDLE,新建‘yieldpro.py’,并写代码如下;

def testcoroutine():

    print ('start')

    c = yield

    print ('over')

print (testcoroutine())

实例讲解Python中的yield协程

2、F5运行程序,并没有打印出‘start’,而是一个生成器。

<generator object testcoroutine at 0x0000000002F62570>

实例讲解Python中的yield协程

3、next触发生成器函数执行(也可以用 send(None)),当yield右侧没有值时,返回None

def testcoroutine():

    print ('start')

    c = yield 

    print ('over')

print (testcoroutine())

mycor = testcoroutine()

print (next(mycor))

实例讲解Python中的yield协程

4、F5运行程序,打印出‘start’和yield返回值‘None’

实例讲解Python中的yield协程

5、给yield左侧赋值要用send,代码如下;

def testcoroutine():

    print ('start')

    c = yield

    print (c)

    print ('over')

print (testcoroutine())

mycor = testcoroutine()

print (next(mycor))

mycor.send(2)

实例讲解Python中的yield协程

6、F5运行程序,最后抛出的异常是正常的,在程序中要捕获这个异常进行处理。

实例讲解Python中的yield协程

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()方法,就不会

实例讲解Python中的yield协程

  • 实例讲解Python迭代器的概念
  • Python中yield使用方法
  • Python __init__()方法实例解读
  • Python实例讲解XPath语法
  • java中 for循环的使用实例
  • 热门搜索
    怎么修改图片大小 户型图怎么画 微笑用英语怎么说 怎么发送文件夹 罗莱家纺怎么样 欧诗漫怎么样 市场分析怎么写 浙江农林大学怎么样 怎么查电脑的ip地址 泰拉瑞亚床怎么做