问题描述
是否可以在 Python 中使用 with
语句声明多个变量?
Is it possible to declare more than one variable using a with
statement in Python?
类似于:
from __future__ import with_statement
with open("out.txt","wt"), open("in.txt") as file_out, file_in:
for line in file_in:
file_out.write(line)
...还是同时清理两个资源的问题?
... or is cleaning up two resources at the same time the problem?
推荐答案
可以在 Python 3 自 v3.1 和 Python 2.7.新的with
语法支持多个上下文管理器:
It is possible in Python 3 since v3.1 and Python 2.7. The new with
syntax supports multiple context managers:
with A() as a, B() as b, C() as c:
doSomething(a,b,c)
与 contextlib.nested
不同,这保证了 a
和 b
将拥有它们的 __exit__()
'即使 C()
或其 __enter__()
方法引发异常,也会调用 s.
Unlike the contextlib.nested
, this guarantees that a
and b
will have their __exit__()
's called even if C()
or it's __enter__()
method raises an exception.
您还可以在以后的定义中使用以前的变量(h/t Ahmad 下面):
You can also use earlier variables in later definitions (h/t Ahmad below):
with A() as a, B(a) as b, C(a, b) as c:
doSomething(a, c)
这篇关于“with"语句中的多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!