在函数内一旦存在yield关键字,调用函数并不会执行函数体代码
会返回一个生成器对象,生成器即自定义的迭代器
触发函数体代码的运行,遇到yield停下来,将yield后的值,当做本次调用的结果返回
def func():
print('一')
yield 1
print('二')
yield 2
print('三')
yield 3
print('四')
f = func()
print(f) # <generator object func at 0x00000221EF4D6148>
res1 = f.__next__()
print(res1)
res2 = f.__next__()
print(res2)
res3 = f.__next__()
print(res3)
res4 = f.__next__()
结果:
<generator object func at 0x0000019772DCEC48>
一
1
二
2
三
3
四
Traceback (most recent call last):
File "D:/test_1/Day18.py", line 174, in <module>
res4 = f.__next__()
StopIteration
def func_range(start, stop, step=1):
while start < stop:
yield start
start += step
func = func_range(1, 5, 2)
print(next(func))
print(next(func))
print(next(func))
结果:
1
3
Traceback (most recent call last):
File "D:/test_1/Day18.py", line 185, in <module>
print(next(func))
StopIteration
for n in range(1, 5, 2):
print(n)
示例1:
# x=yield 返回值
def dog(name):
print(f'{name}准备吃东西啦。。。')
while True:
# x拿到的是yield接收到的值
x = yield # x=''
print(f'{name}吃了{x}')
g = dog('allen')
g.send(None) # 相当于next(g)
g.send(['骨头', '猪肉'])
g.send('羊排')
g.send('牛肉')
g.close()
# g.send('qqqq')
结果:
allen准备吃东西啦。。。
allen吃了['骨头', '猪肉']
allen吃了羊排
allen吃了牛肉
示例2:
def dog(name):
food_list = []
print(f'{name}准备吃东西啦。。。')
while True:
# x拿到的是yield接收的值
x = yield food_list
print(f'{name}吃了{x}')
food_list.append(x)
g = dog('allen')
res = g.send(None) # next(g)
print(res)
res = g.send('骨头')
print(res)
res = g.send('羊排')
print(res)
g.send('猪肉')
结果:
allen准备吃东西啦。。。
[]
allen吃了骨头
['骨头']
allen吃了羊排
['骨头', '羊排']
allen吃了猪肉
示例3:
def func():
print('start......')
x = yield 111
print('hahahahahaha')
print('hahahahahaha')
print('hahahahahaha')
print('hahahahahaha')
yield 222
g = func()
res = next(g)
print(res)
res = g.send('hhhhhhhhhhhh')
print(res)
结果:
start......
111
hahahahahaha
hahahahahaha
hahahahahaha
hahahahahaha
222
总结:
yield关键字,就是自定义迭代器的实现方式;
yield可以返回值,不同于return,函数一旦遇到return就结束了;
而yield可以保存函数的运行状态挂起函数,用来返回多次值。