python 中with的用法

来源:互联网 发布:mac终端输入密码错误 编辑:程序博客网 时间:2024/05/29 09:53
可以用with来保证关闭打开的文件
with open('hello.txt') as f:
    do some file operations
在之前如果要保证关闭文件需要这样:
f = open('hello.txt')
try:
  do some file operations
finally:
  f.close()
为了简化这些操作,pyhton2.5中引入with,在进入with时python会自动调用对象的__enter__ 函数,
离开with时会调用 __exit__ 函数,如下所示。
class SomeThing(object):
    def __enter__(self):
set things up
return self
    def __exit__(self, type, value, traceback):
tear things down
 
0 0
原创粉丝点击