我在某人的代码中看到了这一点。这是什么意思?
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
原文由 zjm1126 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用这些神奇的方法(
__enter__
,__exit__
)允许您实现可以通过with
语句轻松使用的对象。这个想法是它可以很容易地构建需要执行一些“清理”代码的代码(将其视为
try-finally
块)。 这里有更多的解释。一个有用的示例可能是数据库连接对象(一旦相应的“with”语句超出范围,它就会自动关闭连接):
如上所述,将此对象与
with
语句一起使用(如果您使用的是 Python 2.5,则可能需要在文件顶部执行from __future__ import with_statement
)。PEP343 - ‘with’ 语句’ 也有很好的文章。