Python之生成器

1.Python的生成器是一种特殊的迭代器

 1 def create_generator(all_num):
 2     a, b = 0, 1
 3     ind = 0
 4     while ind < all_num:
 5         yield a  # 程序执行到此处等待取值函数不会出栈, yield返回一个生成器模板类似Python class
 6         a, b = b, a+b
 7         ind += 1
 8 
 9 
10 gen_obj = create_generator(10)
11 for num in gen_obj:
12     print(num)
13 
14 gen_obj1 = create_generator(20)
15 
16 print('-'*50)
17 
18 while True:
19     try:
20         print(next(gen_obj1))
21     except StopIteration:
22         print('迭代完成')
23         break
24 
25 print('*'*50)
26 print(gen_obj)
27 print(dir(gen_obj))

  程序输出:

 1 0
 2 1
 3 1
 4 2
 5 3
 6 5
 7 8
 8 13
 9 21
10 34
11 --------------------------------------------------
12 0
13 1
14 1
15 2
16 3
17 5
18 8
19 13
20 21
21 34
22 55
23 89
24 144
25 233
26 377
27 610
28 987
29 1597
30 2584
31 4181
32 迭代完成
33 **************************************************
34 <generator object create_generator at 0x7f134931c360>
35 ['__class__', '__del__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__name__', '__ne__', '__new__', '__next__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'gi_yieldfrom', 'send', 'throw']
36 
37 Process finished with exit code 0
View Code

 2.生成器中的send的方法,send也可以和next一样启动生成器并且可以传入一个值给生成器

   1) 生成器可以选择通过这个传入值可以改变生成器的行为.

原文地址:https://www.cnblogs.com/linxmouse/p/9826573.html