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为止,然后重复删除动作

    公众号请关注:侠之大者
  • 相关阅读:
    strcpy_s 和 strcat_s的用法 简单
    SAP更改商品的授权
    SAP设置默认的登录Client Code
    SAP安装windwos XP Sap的show 教程什么都看不到,的解决办法
    SAP用户管理
    sap 常用事务代码
    SAP-系统表
    随笔
    SAP如何学好SAP BASIS
    SAP IMG
  • 原文地址:https://www.cnblogs.com/kamil/p/5204281.html
Copyright © 2011-2022 走看看