zoukankan      html  css  js  c++  java
  • python的yield语法基础

    生成器总结:

    最普通的例子:

     1 >>> def h():
     2 ... yield 1
     3 ... yield 2
     4 ... yield 3
     5 ... 
     6 >>> c = h()
     7 >>> c.next()
     8 1
     9 >>> c.next()
    10 2
    11 >>> c.next()
    12 3
    13 >>> c.next()
    14 Traceback (most recent call last):
    15 File "<stdin>", line 1, in <module>
    16 StopIteration

    每次调用next都会返回yield后面表达式的值,直到遇到下一个yield语句为止。

    复杂一点的例子:

     1 >>> def h():
     2 ... print '111'
     3 ... yield '+111'
     4 ... print '222'
     5 ... yield '+222'
     6 ... print '333'
     7 ... yield '+333'
     8 ... 
     9 # c是生成器
    10 >>> c = h()
    11 
    12 # 111是print出来的,而+111是yield返回的,这时yield执行完了第一个yield并暂停。
    13 # 直到接受到下一个next()
    14 >>> c.next()
    15 111
    16 '+111'
    17 
    18 >>> c.next()
    19 222
    20 '+222'
    21 >>> c.next()
    22 333
    23 '+333'
    24 # 因为h()已经是一个生成器函数,当所有yield都执行完毕之后,再调用next()就会引发StopIteration错误。
    25 >>> c.next()
    26 Traceback (most recent call last):
    27 File "<stdin>", line 1, in <module>
    28 StopIteration
    29 
    30 >>> 
    31 >>> c = h()
    32 # 111是print的返回值,而x是yield的返回值
    33 >>> x = c.next()
    34 111
    35 >>> x
    36 '+111'
    37 >>> y = c.next()
    38 222
    39 >>> y
    40 '+222'
    41 >>> z = c.next()
    42 333
    43 >>> z
    44 '+333'

    更复杂的例子:

     1 >>> def h():
     2 ... print 'enter yield!'     #1
     3 ... m = yield 123          #2
     4 ... print m             #3
     5 ... d = yield 456          #4
     6 ... print d             #5
     7 ... print 'leave yield!'    #6
     8 ... 
     9 >>> c = h()        # c是一个生成器,因为python认为h()则是一个生成器函数,不是一个普通函数。
    10 >>> a = c.next()    # 往下执行代码,直到遇到yield为止,会返回yield的值
    11 enter yield!       # 这里的'enter yield!'是执行#1打印的,因为要运行到#2,所以必须要打印这一行
    12 >>> a           # 而#3返回了yield后面表达式的值
    13 123
    14 >>> b = c.next()    # 再次调用next()执行到了#4,返回了yield的值。 但是yield的总的返回值总是None,所以返回了None.
    15 None
    16 >>> b     # 但是b的值是yield返回的,是456
    17 456

     

  • 相关阅读:
    【转】Java抽象类与接口的区别
    【转】java方法参数传递方式--按值传递、引用传递
    关联mysql失败_Server returns invalid timezone. Go to 'Advanced' tab and set 'serverTimezon'
    分词器的安装与使用
    Mysql、ES 数据同步
    ES、kibana安装及交互操作
    tl-wr742n 怎么设置dns
    tl-wr742n无线路由器怎么设置
    PowerMock学习(十一)之Mock private methods的使用
    PowerMock学习(十)之Mock spy的使用
  • 原文地址:https://www.cnblogs.com/huazi/p/2491461.html
Copyright © 2011-2022 走看看