to your module:
要在Python 2.5里面用with语句,你得在module里面加上下面这行:
from __future__ import with_statement
The statement will always be enabled in Python 2.6.
等到了Python 2.6,你就不用再这么麻烦了。
Some standard Python objects now support the context management protocol and
can be used with the 'with' statement. File objects are one example:
有些Python对象已经实现了context management接口,因此现在就可以用在with语句里里。
File对象就是一例:
with open('/etc/passwd', 'r') as f:
for line in f:
print line
... more processing code ...
After this statement has executed, the file object in f will have been
automatically
closed, even if the 'for' loop raised an exception part-way through the block.
只要这个语句运行结束,即便是因为 for 循环运行到一半的时候抛出了异常,
file对象f也会自动关闭。
The threading module's locks and condition variables also support the
'with' statement:
threading模块的lock和condition对象也支持with 语句
(据shhgs得理解,这里的locks表示threading里面的所有lock,如Lock, RLock都已经支持with了):
lock = threading.Lock()
with lock:
# Critical section of code
...
The lock is acquired before the block is executed and always released
once the block
is complete.
执行block之前得先得到lock,然后执行完毕之后会释放锁。
The decimal module's contexts, which encapsulate the desired precision
and rounding
characteristics for computations, provide a context_manager() method
for getting a
context manager:
decimal模块提供了一个能返回context对象的context_manager()方法(请注意看注释,
至少Py2.5b1里面是没有这个方法,你得用get_manager() ),这个context对象
(context是上下文的意思)将计算的精度和近似要求封装了起来
(什么叫上下文?这才叫上下文!Perl的那个上下文根本就是假冒伪劣):
import decimal
# Displays with default precision of 28 digits
v1 = decimal.Decimal('578')
print v1.sqrt()
ctx = decimal.Context(prec=16)
#----------------------------------------
# 根据shhgs的试验,ctx对象是没有context_manager()方法的,
# 你得
# with ctx.get_manager() :
#----------------------------------------
| 论坛热门帖子: | [lch203] 写得蛮好的linux学习笔记(10-21) [黑马制造] 学习java的30个目标(10-19) [笑傲股林] 做测试半年了,有点迷茫,应该再学些什么提高自己的测试水平和测试能力呢?(10-19) [udp8589] 大家用google的来吱一声? 用百度的~~也来报道下?(10-18) [沂偌掳兆] 本人总结的一些认为C++比较经典的书籍,希望对大家有用(10-18) |
| TAG标签: | with 一个 对象 语句 这个 方法 异常 如果 可以 返回 |
注册
个人空间
