zoukankan      html  css  js  c++  java
  • yield和send函数

    yield作用类似于return,其本质是一个迭代器。

    当程序执行到yield时,会结束本次循环,返回一个值,然后内置含有next()函数,

    下次在执行时,会从yield结束的地方继续执行。

    带yield的函数是一个生成器,内置next函数,当本次执行到yield结束时候,下一次next就会从本次停止的地方继续执行,

    碰到yield时候,就会return生成的数。

    send函数

    send函数给参数赋值,其执行过程也是从上一步的yield结束的时候开始。

    给出一段代码参考:

    1 def foo():
    2     print("starting...")
    3     while True:
    4         res = yield 4
    5         print("res:",res)
    6 g = foo()
    7 print(next(g))
    8 print("*"*20)
    9 print(next(g))

    其结果:

    1 starting...
    2 4
    3 ********************
    4 res: None
    5 4

    send函数:

    1 def foo():
    2     print("starting...")
    3     while True:
    4         res = yield 4
    5         print("res:",res)
    6 g = foo()
    7 print(next(g))
    8 print("*"*20)
    9 print(g.send(7))

    其结果:

    1 starting...
    2 4
    3 ********************
    4 res: 7
    5 4
  • 相关阅读:
    mysql-规避重复插入
    redis-string
    redis-map
    跨库修改
    Python-批量插入
    Python-批量修改
    MongoDB操作符
    Cron表达式
    Mycat修改空指针问题
    项目中常用的linux命令
  • 原文地址:https://www.cnblogs.com/ywheunji/p/10448395.html
Copyright © 2011-2022 走看看