对于某些任务,通常需要多个具有明确释放资源的对象 - 例如,两个文件; 当任务是使用嵌套with块的函数的本地任务时,这很容易完成,或者 - 甚至更好 - with具有多个with_item子句的单个块:
with open('in.txt', 'r') as i, open('out.txt', 'w') as o:
# do stuff
Run Code Online (Sandbox Code Playgroud)
OTOH,当这些对象不仅仅是函数作用域的本地对象,而是由类实例拥有 - 换句话说,上下文管理器如何构成时,我仍然很难理解它应该如何工作.
理想情况下,我想做的事情如下:
class Foo:
def __init__(self, in_file_name, out_file_name):
self.i = WITH(open(in_file_name, 'r'))
self.o = WITH(open(out_file_name, 'w'))
Run Code Online (Sandbox Code Playgroud)
并有Foo自己变成上下文管理,处理i和o,这样,当我做
with Foo('in.txt', 'out.txt') as f:
# do stuff
Run Code Online (Sandbox Code Playgroud)
self.i并self.o按照您的预期自动处理.
我修改了写东西,比如:
class Foo:
def __init__(self, in_file_name, out_file_name):
self.i = open(in_file_name, 'r').__enter__()
self.o = open(out_file_name, 'w').__enter__()
def __enter__(self):
return …Run Code Online (Sandbox Code Playgroud)