python之yield
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:wadeson
'''
def foo():
print("----------------start--------------")
while True:
m = yield 5 #5是next方法打印之后的返回值,m是next方法取出的值,yield就是间断跳转
print(m)
print("-------------stop--------------")
g = foo()
g.__next__() #这只是取出generator的值,如果print(g.__next__())将会将生成器的值和返回值都打印出来
for i in range(5):
g.send(i)
----------------start--------------
0
-------------stop--------------
1
-------------stop--------------
2
-------------stop--------------
3
-------------stop--------------
4
-------------stop--------------
#将数据塞入到生成器中
def bar(N):
for i in range(N):
yield i*2
g = bar(5)
for i in g:
print(i)
def foo():
print("-----------------start-------------------")
while True:
m = yield #当执行这一行的时候,遇到yield后跳转到下面的for循环,g.sned(),而m即是send方法推送进来的i的值
#每次循环到yield都会跳转到g.send()
print(m)
print("-------------stop--------------------")
g = foo()
g.__next__()
for i in range(6):
g.send(i)
def bar():
print("-----start-----")
m = yield 5
print(m)
d = yield 12
print(d)
print("-----stop------")
g = bar()
m = g.__next__()
d = g.send('huang')
print(m,d)
运行步骤:
1、g = bar()声明将bar生成器赋予给变量g
2、执行生成器g.__next__()-----》于是转入到生成器内部-----》打印print("-----start-----")
m = yield 5并执行此行,遇见yield于是跳转,但是返回数值5给m{m = g.__next__()}
3、然后执行g.send('huang'),将字符串huang推送到生成器m,并打印print(m)也就是打印了m的值:huang,执行d = yield 12,遇见yield
进行跳转d = g.send('huang')这个的返回值为12
所以最后打印print(m,d)----》5,12(打印这个之前打印了start、huang)
'''
def foo():
print("----------start---------------")
r = ''
m = yield r
print("m---->",m)
d = yield 12
print(d)
print("---------stop-----------------")
def bar():
g = foo()
m = g.__next__()
print("m---",m)
g.send('huang')
print("-------------end--------------")
bar()