是这个代码吗
with open(myfile) as f:
data = f.read()
process(data)
相当于这个
try:
f = open(myfile)
data = f.read()
process(f)
finally:
f.close()
或者下面的一个?
f = open(myfile)
try:
data = f.read()
process(f)
finally:
f.close()
本文:http://effbot.org/zone/python-with-statement.htm http://effbot.org/zone/python-with-statement.htm表明(如果我理解正确的话)后者是正确的。然而,前者对我来说更有意义。如果我错了,我错过了什么?
根据文档 https://www.python.org/dev/peps/pep-0343/:
提出了一个新的语句,其语法如下:
with EXPR as VAR:
BLOCK
上述声明的翻译是:
mgr = (EXPR)
exit = type(mgr).__exit__ # Not calling it yet
value = type(mgr).__enter__(mgr)
exc = True
try:
try:
VAR = value # Only if "as VAR" is present
BLOCK
except:
# The exceptional case is handled here
exc = False
if not exit(mgr, *sys.exc_info()):
raise
# The exception is swallowed if exit() returns true
finally:
# The normal and non-local-goto cases are handled here
if exc:
exit(mgr, None, None, None)
这是你的扩展版本second代码片段。初始化先于try ... finaly
block.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)