阅 读 文 章

Py 2.5 what's new 之 with

[来源:网上转载 (http://www.chinaunix.net) | 作者:网友(shhgs) | 时间:2007-05-27 | 浏览:人次 ]


with和yield是Py 2.5的两大亮点。6月24日我在Python Chinese邮件列表上发布了《 Py 2.5 what's new 之 with》。现在一并贴过来。分隔线以下部分就是邮件的内容。

=====================================================


Python 2.5的beta 1出来了。每次拿到新版本的时候,总是先看what's new。这次看with的时候,发现与先前PEP
310的有很大不同。2.5最终实现的是PEP343。

下面是我翻译的what's new。第一次接触with,谬误指出请大家包涵。

---------------------------------------------------------------------------------------------------------
8 PEP 343: The 'with' statement

The 'with' statement clarifies code that previously would use try...finally
blocks to ensure that clean-up code is executed. In this section, I'll discuss
the statement as it will commonly be used. In the next section, I'll
examine the
implementation details and show how to write objects for use with this
statement.

'with' 语句的功能是执行清理代码,它要比了我们过去用的 try ... finally清楚得多。
本章我会先探讨它是怎么用的,然后再研究其实现的细节,并且写一个能给 with 语句用的对象。

The 'with' statement is a new control-flow structure whose basic structure is:

'with' statement是一个新的流程控制结构,其基本的语法如下:


with expression [as variable]:
   with-block

The expression is evaluated, and it should result in an object that
supports the
context management protocol. This object may return a value that can optionally
be bound to the name variable. (Note carefully that variable is not
assigned the
result of expression.) The object can then run set-up code before with-block is
executed and some clean-up code is executed after the block is done,
even if the
block raised an exception.

(with语句会)先计算表达式,得到一个实现context management接口(这里pep作者使用了protocol,
而不是大家都比较熟悉的interface的术语)的对象。这个对象可能会返回一个值,而你则可以选择
是不是把这个值绑定到变量名("name variable")上。(请注意,这不是将表达式到值赋值给变量。)
然后对象先运行预备代码("set-up code"),再执行with-block,最后在离开block的时候,
即便是因为发生了异常,它也会执行清理代码。

To enable the statement in Python 2.5, you need to add the following directive
论坛热门帖子: [lch203] 写得蛮好的linux学习笔记(10-21)
[黑马制造] 学习java的30个目标(10-19)
[笑傲股林] 做测试半年了,有点迷茫,应该再学些什么提高自己的测试水平和测试能力呢?(10-19)
[udp8589] 大家用google的来吱一声? 用百度的~~也来报道下?(10-18)
[沂偌掳兆] 本人总结的一些认为C++比较经典的书籍,希望对大家有用(10-18)
TAG标签: with 一个 对象 语句 这个 方法 异常 如果 可以 返回

最新评论 共有0位网友发表了评论

发表评论

评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名:(注册)
密码:
验证码:
匿名发表

网站地图友情连接交流论坛网站投稿广告服务联系我们留言本站长统计
Some rights reserved: www.chmhome.com, 鄂ICP备07010232号 E-mail:chinakafei@live.com,QQ:552766
中国咖啡技术网(Chmhome):国外编程技术书籍,中文编程手册,经典编程文章,交流技术,技术软件下载,计算机论文,毕业论文.