生成器的使用注意

主要是生成器中return的作用,以及生成器的send()方法

 1 def Fibnacc(num):
 2     a= 1
 3     b = 1
 4     current_index = 0
 5     while current_index<num:
 6         data = a
 7 
 8         current_index+=1
 9         a,b=b,a+b
10         send_cont = yield data
11         print("执行到这,马上执行return")
12         if send_cont==2:
13             return "我可以让生成器结束奥"
14 #         yield:1.充当返回值的作用2.保存程序的运行状态,并且暂停程序执行3.当next的时候,可以继续换行程序从yield位置继续向下
15 #             执行
16 # 在生成器中使用return实际上就是让生成器结束
17 
18 if __name__ == '__main__':
19     fib = Fibnacc(6)
20     value = next(fib)
21     print(value)
22     try:
23         value =fib.send(2)    #生成器.send(num)  num的值被传递到了send_cont处去了
24         print(value)
25     except Exception as e:
26         print(e)
27     # 在生成器中使用return,返回来的值实际上就是异常的输出   StopIteration: 我可以让生成器结束奥

 

posted @ 2019-12-05 20:47  不识人间花火  阅读(186)  评论(0编辑  收藏  举报