在平时工做中总会有这样的任务,它们须要开始前作准备,而后作任务,而后收尾清理....好比读取文件,须要先打开,读取,关闭python
这个时候就可使用with简化代码,很方便post
1.没有用with语句spa
1
2
3
|
f
=
open
(
'./test.txt'
)
f.read()
f.close()
|
2.使用with语句code
1
2
|
with
open
(
'./test.txt'
) as f:
f.read()
|
with的工做原理是?blog
with 中包含 __enter__ 与 __exit__ 方法, 执行顺序是,在with下面语句未执行前,先执行__enter__方法,with下语句执行结束后,最后执行__exit__.ci
自定义一个上下文管理协议,看一下它的原理博客
1
2
3
4
5
6
7
8
9
10
11
12
|
class
Context():
def
__enter__(
self
):
print
(
'start'
)
return
self
def
__exit__(
self
,
*
unused):
print
(
'over'
)
def
dosomething(
self
):
print
(
'dosomething'
)
with Context() as ctx:
ctx.dosomething()
|
打印结果string
startit
dosomethingio
over
1
|
<em
id
=
"__mceDel"
><em
id
=
"__mceDel"
><br><br><
/
em><
/
em>
|