python with
with 的作用很像 try…except…finally
file = open("/tmp/foo.txt")
try:
data = file.read()
finally:
file.close()
相当于
with open("/tmp/foo.txt") as f:
data = file.read()
with 的原理可以看这里
而不得不说的是,with有两个方法:__enter__(), __exit__()
。
with在执行的最后默默的为你做了一些事情,比如,读文件最后的关闭文件,跟连接池建立连接之后的断开连接等。
还没有评论,来说两句吧...