with ctx.context_manager():
# All code in this block uses a precision of 16 digits.
# The original context is restored on exiting the block.
print v1.sqrt()
8.1 Writing Context Managers
Under the hood, the 'with' statement is fairly complicated.
Most people will only use 'with' in company with existing objects
and don't need to know these details, so you can skip the rest of
this section if you like. Authors of new objects will need to understand
the details of the underlying implementation and should keep reading.
'with'语句背后的实现是相当复杂的。绝大多数人只需要知道怎样把现成的对象用到with里面,
所以只要你觉得合适,完全可以跳过下面这段。但是如果你要写能给with用的对象,
那就得受累读下去了。
A high-level explanation of the context management protocol is:
context management 接口的大致概括如下:
The expression is evaluated and should result in an object called a
``context manager''. The context manager must have __enter__() and
__exit__() methods.
(with语句先)计算表达式,拿到一个被成为context manager(上下文管理器)的对象。
这个context manager必须提供__enter__()和__exit__()方法。
The context manager's __enter__() method is called.
The value returned is assigned to VAR.
If no 'as VAR' clause is present, the value is simply discarded.
然后(with)再调用context manager的__enter__()方法。
如果语句里面还有'as VAR',那么它会顺手把(__enter__()所返回的)值赋给VAR。
如果没有'as VAR',这个值就丢了。
The code in BLOCK is executed.
然后执行BLOCK。
If BLOCK raises an exception, the __exit__(type, value, traceback) is called
with the exception details, the same values returned by sys.exc_info().
The method's return value controls whether the exception is re-raised:
any false value re-raises the exception, and True will result in
suppressing it.
You'll only rarely want to suppress the exception, because if you do the author
of the code containing the 'with' statement will never realize
| 论坛热门帖子: | [lch203] 写得蛮好的linux学习笔记(10-21) [黑马制造] 学习java的30个目标(10-19) [笑傲股林] 做测试半年了,有点迷茫,应该再学些什么提高自己的测试水平和测试能力呢?(10-19) [udp8589] 大家用google的来吱一声? 用百度的~~也来报道下?(10-18) [沂偌掳兆] 本人总结的一些认为C++比较经典的书籍,希望对大家有用(10-18) |
| TAG标签: | with 一个 对象 语句 这个 方法 异常 如果 可以 返回 |
注册
个人空间
