python with原理

时间:2023-03-08 23:54:30
python with原理

在python2.5+中可以用with来保证关闭打开的文件

with open('hello.txt') as f:
do some file operations

为什么要引入with呢?

在之前如果要保证关闭文件需要这样:

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

是不是很简单?

比如我们可以实现一个自动释放资源的connection类

class Connection(object):
def __enter__(self):
print 'enter'
return self def __exit__(self, type, value, traceback):
print 'exit' def say_hi(self):
print 'hello, world' def open_connection():
return Connection() with open_connection() as conn:
conn.say_hi()

程序输出为:

enter
hello, world
exit