Python 'yield' - Dive into sample code
来源:互联网 发布:java中this调用方法 编辑:程序博客网 时间:2024/06/06 04:27
Python yield
Official introduction to 'yield':
https://docs.python.org/2.7/reference/simple_stmts.html?highlight=yield#grammar-token-yield_stmt
It is said 'yield' statement can optimize code efficiency.
Here is the detailed post to help understand its advantage.
http://blog.csdn.net/preterhuman_peak/article/details/40615201
The code below is adapted from an example in Core Python Programming.
def counter(start_at=0): count = start_at while count < 6: val = (yield count) if val is not None: count = val else: count += 1 # for i in counter(1):# print i c = counter(1) print c.next()print c.next()print c.next()print c.next()print c.next()
Based on my observation during debugging, the line 'val
=
(
yield
count)
' is crucial.
The execution sequence is as follows:
c
=
counter(
1
)
This doesn't execute the 'counter' function. You will go to the first '
print
c.
next
()
', if you try to step into during debugging.c.
next
()
in line
printc.
next
()
Step into, you will go to the 'counter' function now.
yield
count
Starting from the 1st line of the function, you will jump out of it to
print
c.
next
()
while 'yield
count
' in 'val
=
(
yield
count)
' is executed.print
c.
next
()
val
=
(
yield
count)
After printing, you go back inside 'counter' function again and start execute from below 'yield'. Here it is the value assignment for 'val'.
Note before Step #5, val is not defined. Afterwards, val is None, which mean (yield count) doesn't return anything. It's just like a markup telling you that 'count' is the thing to output when you call next().
count
+
=
1
while
count <
6
yield
count
print
c.
next
()
- Python 'yield' - Dive into sample code
- Dive Into Python
- Dive into Python 点滴
- dive into python (2)
- dive into python (3)
- dive into python
- Dive Into Python学习日志
- dive into Python (1)
- 深入 Python :Dive Into Python 中文版
- Dive into Python(深入Python) 读书笔记
- 决定开始翻译Dive Into Python
- Dive into python--3.12. 一次赋多个值
- 为什么《Dive into Python》不值得推荐
- <Dive into Python>大补贴
- Reading Notes on "Dive Into Python"
- 《Dive Into Python》非死不可
- 《Dive into Python》读书笔记之正则表达式
- [Dive into Python:第三章]内置数据类型
- dubbo 学习
- 开源日志系统 log4c 使用心得+总结
- iGrimace 安装
- 关于base64编码的原理及实现
- 函数式编程以及lambda 运算符的看法
- Python 'yield' - Dive into sample code
- Aws bmp 安装之后,启动服务之后无法访问
- python subprocess 2
- iOS探索:iOS程序的Build过程
- 浅谈Struts2拦截器的原理与实现
- STRUTS2 登录拦截器
- Java ClassLoader详解及应用(写的挺好的)
- Arcgis for Silverlight的图例Legend默认折叠
- linux下service的命令用法