关于Generator
使用for循环获取内容
代码
def met():
#第一部分起
print("step 1")
yield #第一部分终
#第二部分起
print("step 2")
yield 4 #第二部分终
#三起
print("step 3")
yield "asd" #三终
#四起
print("step 4")
yield [1,2,3] #四终
#五起
print("step 5")
yield (1,2,3) #五终
#六起
print("step 6")
yield (print("*****")) #六终
#七起
print("step 7")
print("Almost done...")
#七终
return("Done...")
Gen=met()
for i in Gen:
print(type(i))
print()
运行结果
step 1
<class 'NoneType'>
step 2
<class 'int'>
step 3
<class 'str'>
step 4
<class 'list'>
step 5
<class 'tuple'>
step 6
*****
<class 'NoneType'>
step 7
Almost done...
-
六个yield把met这个生成器切分成了七部分,每次执行一个部分,最后一个是第六个yield和return中间的代码,使用for循环是执行不到return的
-
生成器中的每个i是每个yield后面的数据,如果不是基本数据类型而是类似print这样的语句(第六部分),那么会视作
#六起
print("step 6")
print("*****")
yield #六终
所以第六次的 i 是None
使用next()获取内容
调用七次next()的代码
def met():
#第一部分起
print("step 1")
yield #第一部分终
#第二部分起
print("step 2")
yield 4 #第二部分终
#三起
print("step 3")
yield "asd" #三终
#四起
print("step 4")
yield [1,2,3] #四终
#五起
print("step 5")
yield (1,2,3) #五终
#六起
print("step 6")
yield (print("*****")) #六终
#七起
print("step 7")
print("Almost done...")
#七终
return("Done...")
Gen=met()
for i in range(7):
print(next(Gen))
print()
运行结果
第七次调用next()后生成器的七部分已全部调用完毕,此时抛出StopIteration的异常,其value为return的值
增加了异常捕获的代码
def met():
#第一部分起
print("step 1")
yield #第一部分终
#第二部分起
print("step 2")
yield 4 #第二部分终
#三起
print("step 3")
yield "asd" #三终
#四起
print("step 4")
yield [1,2,3] #四终
#五起
print("step 5")
yield (1,2,3) #五终
#六起
print("step 6")
yield (print("*****")) #六终
#七起
print("step 7")
print("Almost done...")
#七终
return("Done...")
Gen=met()
while True:
try:
print(type(next(Gen)))
print()
except StopIteration as SI:
print()
print("return value is ",SI.value)
break
运行结果
step 1
<class 'NoneType'>
step 2
<class 'int'>
step 3
<class 'str'>
step 4
<class 'list'>
step 5
<class 'tuple'>
step 6
*****
<class 'NoneType'>
step 7
Almost done...
return value is Done...
用这种方法可得到return的值
使用send()
def met():
while True:
receive=yield(1)
#receive用于接收send进来的值
print("Extra "+str(receive))
Gen=met()
#print(next(Gen))
print(Gen.send(None))
#用next或者send(None)来启动
#执行到receive=yield(1)时中断,将yield的参数1返回给Gen.send(None)
#所以第一次输出1
print(Gen.send("Hello"))
#将"Hello"赋给receive
#继续从print("Extra "+str(receive))处执行
#输出Extra Hello
#循环,将yield的参数1返回给Gen.send("Hello")
#输出1,中断
运行结果
1
Extra Hello
1