zoukankan      html  css  js  c++  java
  • yield实例

    如下

    # __author__ = liukun
    # coding:utf-8
    def it():
        print ('hello')
        yield 1
        yield 1
    a= it()
    print("#############")
    print(a)
    print("*************")
    for i in a:
        print (i)

    结果:

    /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Applications/PyCharm.app/Contents/helpers/pycharm/utrunner.py /Users/kamil/PycharmProjects/untitled4/Day5/python基础教程/test.py true
    Testing started at 下午4:33 ...
    #############
    <generator object it at 0x1016babf8>
    *************
    hello
    1
    1
    
    Process finished with exit code 0
    Empty test suite.

    从上面可以看出当执行generator函数的时候仅仅做的是生成了一个特殊的iterator对象,并没有执行里面的内容

    再来

    a = 1
    def it():
        global a
        yield 3
        a += 1
        yield 4
    for i in it():
        print ("i=%d;a=%d" %(i,a))

    '''

    i=3;a=1
    i=4;a=2

    '''

     如果:

    a = 1
    def it():
        global a
        a += 1
        yield 3
        yield 4
    for i in it():
        print ("i=%d;a=%d" %(i,a))
    '''

    i=3;a=2
    i=4;a=2


    '''

    yield的作用就是,每次发生next()调用,函数执行完yield语句之后在挂起,这时返回yield的值(你愿意yield啥就yield啥),整个函数状态被保存,等待下一次next()调用;下次next()调用发生时,从yield后的语句开始执行(有yiled也在循环体内,未必一定是顺序的),直到再次遇到yield为止,然后重复删除动作

    公众号请关注:侠之大者
  • 相关阅读:
    Spring Boot 使用mysql数据库
    Nginx开启Gzip压缩大幅提高页面加载速度
    构建微服务:Spring boot 入门篇
    Python时间戳和日期的相互转换
    【Mongodb】aggregate限制返回字段
    MongoDB的skip,limit,sort执行顺序
    结对-结对四则运算生成器-最终程序
    C# List分页
    c# List的排序
    C#并行编程-Parallel
  • 原文地址:https://www.cnblogs.com/kamil/p/5204281.html
Copyright © 2011-2022 走看看