解释Python的'__enter__'和'__exit__'
我在某人的代码中看到了这一点。这是什么意思?
def __enter__(self):
return self
def __exit__(self, type, value, tb):
self.stream.close()
from __future__ import with_statement#for python2.5
class a(object):
def __enter__(self):
print 'sss'
return 'sss111'
def __exit__(self ,type, value, traceback):
print 'ok'
return False
with a() as s:
print s
print s
-
使用这些魔术方法(
__enter__
,__exit__
)使您可以实现可轻松用于该with
语句的对象。这个想法是,它使构建需要执行一些“清除”代码的代码(将其视为一个
try- finally
块)变得容易。这里有更多的解释。一个有用的例子是数据库连接对象(一旦对应的“ with”语句超出范围,它就会自动关闭连接):
class DatabaseConnection(object): def __enter__(self): # make a database connection and return it ... return self.dbconn def __exit__(self, exc_type, exc_val, exc_tb): # make sure the dbconnection gets closed self.dbconn.close() ...
如上所述,将此对象与
with
语句一起使用(from __future__ import with_statement
如果您使用的是Python
2.5,则可能需要在文件顶部进行操作)。with DatabaseConnection() as mydbconn: # do stuff
PEP343-‘with’语句’也有不错的写法。