理解Python的Withas语句《python标准库》上这么⼀句话:
with open('filename', 'wt') as f:
f.write('hello, world!')
我不明⽩为什么这样写,下⾯这篇⽂章对此做出了解释
------------------
There are two annoying things here. First, you end up forgetting to close the file handler. The second is how to handle exceptions that may occur once the file handler has been obtained. One could write something like this to get around this:
这⾥有两个问题。⼀是可能忘记关闭⽂件句柄;⼆是⽂件读取数据发⽣异常,没有进⾏任何处理。下⾯是处理异常的加强版本:
1
2
3
file = open
(
"/"
)
data
= file
.read()
file
.close()
While this works well, it is unnecessarily verbose. This is where with is useful. The good thing about with apart from the better syntax is that it is very good handling exceptions. The above code would look like this, when using with:
虽然这段代码运⾏良好,但是太冗长了。这时候就是with ⼀展⾝⼿的时候了。除了有更优雅的语法,with 还可以很好的处理上下⽂环境产⽣的异常。下⾯是with
1
2
3
4
5
file = open ( "/"
)
try
:
data
= file
.read()
finally
:
file
.close()
版本的代码:
while this might look like magic, the way Python handles with is more clever than magic. The basic idea is that the statement after with has to evaluate an o bject that responds to an __enter__() as well as an __exit__() function.
这看起来充满魔法,但不仅仅是魔法,Python 对with 的处理还很聪明。基本思想是with 所求值的对象必须有⼀个__enter__()⽅法,⼀个__exit__()⽅法。
After the statement that follows with is evaluated, the __enter__() function on the resulting object is called. The value returned by this function is assigned t o the variable following as. After every statement in the block is evaluated, the __exit__() function is called.
紧跟with 后⾯的语句被求值后,返回对象的__enter__()⽅法被调⽤,这个⽅法的返回值将被赋值给as 后⾯的变量。当with 后⾯的代码块全部被执⾏完之后,将调⽤前⾯返回对象的__exit__()⽅法。
1
2
with open
(
write的返回值"/"
) as
file
:
data
= file
.read()
This can be demonstrated with the following example:下⾯例⼦可以具体说明with如何⼯作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19#!/usr/bin/env python # with_example01.py
class
Sample:
def
__enter__(
self
):
print
"In __enter__()"
return
"Foo"
def
__exit__(
self
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论