[Python 学习]2.5版yield之学习心得
shhgs 发布了关于《 Py 2.5 what's new 之 yield
》
之后,原来我不是特别关注 yield 的用法,因为对于2.3中加入的yield相对来说功能简单,它是作为一个 generator
不可缺少的一条语句,只要包含它的函数即是一个 generator 。但在2.3中,generator
不能重入,不能在运行过程中修改,不能引发异常,你要么是顺序调用,要么就创建一个新的 generator。而且 generator 中的
yield 只是一个语句。但到了 2.5 版之后,情况发生了很在的变化。
在 shhgs 的文章中对于 yield 并没有做太多的描述,也因此让我在理解上产生了许多问题,于是我仔细地研究了 What's new
和 PEP 342
文档,有了一些体会,描述在下面。
这里不说为什么要对 yield 进行修改,只说功能。
1. yield 成为了表达式,它不再是语句,但可以放在单独的行上。原文:
Redefine "yield" to be an expression, rather than a statement. The
current yield statement would become a yield expression whose value is
thrown away.
可以看到,如果你还是写成语句形式的话,其实还是一个表达式,只是它的值被扔掉了。
那么一个 yield 表达式可以这样写:
x = yield i
y = x + (yield x)
那么这种机制到底是如何工作的呢?在2.3版很容易理解,你完全可以把 yield 语句理解为一个 "return" 语句,只不过
"return" 完后,函数并不结束,而是断续运行,直到再次遇到 yield 语句。那么到了 2.5 版不仅仅是一个 "return"
语句那么简单了,让我们看完下面关于 send() 的说明再描述它吧。
2. 增加了 send(msg) 方法,因此你可以使用它向 generator 发送消息。原文:
Add a new send() method for generator-iterators, which resumes the
generator and "sends" a value that becomes the result of the current
yield-expression. The send() method returns the next value yielded by
the generator, or raises StopIteration if the generator exits without
yielding another value.
执行一个 send(msg) 会恢复 generator 的运行,然后发送的值将成为当前
yield 表达式的返回值
。然后 send() 会返回下一个被 generator yield 的值,如果没有下一个可以 yield 的值则引发一个异常。
那么可以看过这其实包含了一次运行,从将msg赋给当前被停住的 yield 表达式开始,到下一个 yield 语句结束,然后返回下
相关文档:
php版:
<?php
$cookie_file = fopen('cookie.txt','w');//dirname(__FILE__)."/cookie_".md5(basename(__FILE__)).".txt"; // 设置Cookie文件保存路径及文件名
function vlogin($url,$data){ // 模拟登录获取Cookie函数
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($cur ......
Python基本安装:
* http://www.python.org/ 官方标准Python开发包和支持环境,同时也是Python的官方网站;
* http://www.activestate.com/ 集成多个有用插件的强大非官方版本,特别是针对Windows环境有不少改进;
Python文档:
* http://www.pyth ......
PyRSS2Gen :rss生成
下载地址:http://www.dalkescientific.com/Python/PyRSS2Gen-1.0.0.tar.gz
例子:
Java代码
import datetime
import PyRSS2Gen
rss = PyRSS2Gen.RSS2(
title = " ......
转自 http://hi.baidu.com/xunxun129/blog/item/3befad0f8ff992c07bcbe180.html
有时我们需要在 Python 中使用 zip 文件,而在1.6版中,Python 就已经提供了 zipfile 模块可以进行这样的操作。不过 Python 中的 zipfile 模块不能处理多卷的情况,不过这种情况并不多见,因此在通常情况下已经足够使用了。下面我只是对 ......