首页 > 代码库 > Python Generator

Python Generator

  本文对《Python Cookbook》中对于生成器部分的讲解进行总结和分析:

  对于生成器我们一般这样使用:

lxw Python_Cookbook$ pPython 3.4.0 (default, Apr 11 2014, 13:05:18) [GCC 4.8.2] on linuxType "help", "copyright", "credits" or "license" for more information.>>> def countdown(n):...     print("Start to count from", n)...     while n > 0:...          yield n...          n -= 1...     print("Done!")... >>> c = countdown(3)>>> c<generator object countdown at 0xb7234c5c>>>> for item in c:...     print(item)... Start to count from 3321Done!

  我想说的是, 让我们来看一下生成器的底层工作机制(underlying mechanics):[接上面的代码]

>>> d = countdown(3)>>> d<generator object countdown at 0xb711a43c>>>> next(d)Start to count from 33>>> next(d)2>>> next(d)1>>> next(d)Done!Traceback (most recent call last):  File "<stdin>", line 1, in <module>StopIteration>>> 

 

Python Generator