快速理解yield

on under python
1 minute read

0x1 理解

理解下面2个脚本的运行结果

脚本1:

def a():
    print(111)

def b():
    flag='od'
    print("test")
    yield 1
    flag='ida'
    print("nihao")
    yield 2
    print("wohao")
    print(flag)

f1=a()
f2=b()

print("before for loop")

for i in f2:
    print(i,type(i))
    print(666)

print("after for loop")

运行结果如下:

111
before for loop
test
1 <class 'int'>
666
nihao
2 <class 'int'>
666
wohao
ida
after for loop

脚本2:

def h():
    print('Wen Chuan')
    m = yield 5  # Fighting!
    print(999999999999)
    d = yield 12
    print('We are together!')

c = h()
tmp=next(c)  #相当于c.send(None)
print(11111111111)
print(tmp)
print(222)
tmp=c.send('Fighting!')  #(yield 5)表达式被赋予了'Fighting!'
print(3333)
print(tmp)

运行结果如下:

Wen Chuan
11111111111
5
222
999999999999
3333
12
yield, python
home
github
archive
category