本文对《Python Cookbook》中对于生成器部分的讲解进行总结和分析:
对于生成器我们一般这样使用:
lxw Python_Cookbook$ p Python 3.4.0 (default, Apr 11 2014, 13:05:18) [GCC 4.8.2] on linux Type "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 3 3 2 1 Done!
我想说的是, 让我们来看一下生成器的底层工作机制(underlying mechanics):[接上面的代码]
>>> d = countdown(3) >>> d <generator object countdown at 0xb711a43c> >>> next(d) Start to count from 3 3 >>> next(d) 2 >>> next(d) 1 >>> next(d) Done! Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>>
时间: 2024-10-13 23:22:08