之前一直觉得yield和return差别不大,只是不直接返回,下面这个例子可以直观展示两者的差别:
yield相当于按兵不动
return碰到就是返回
def testyield():
response=''
try:
for i in range(0,20):
response=str(i)
yield response+'_stop_'
except:
print('wrong')
yield "/././"
def testreturn():
response = ''
try:
for i in range(0, 20):
response = str(i)
return response + '-stop-'
except:
print('wrong')
return "-end-"
if __name__ == '__main__':
res=testyield()
for r in res:
print(r)
print('-------------------------分割线---------------')
res2=testreturn()
for r2 in res2:
print(r2)
结果:
0_stop_
1_stop_
2_stop_
3_stop_
4_stop_
5_stop_
6_stop_
7_stop_
8_stop_
9_stop_
10_stop_
11_stop_
12_stop_
13_stop_
14_stop_
15_stop_
16_stop_
17_stop_
18_stop_
19_stop_
/././
-------------------------分割线---------------
0
-
s
t
o
p
-