有没有一种 Pythonic 的方式来自动自动__exit__处理一个类的所有成员?
class C:
def __init__(self):
self.a = open('foo')
self.b = open('bar')
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
# Is it correct to just forward the parameters here?
self.a.__exit__(self, exc_type, exc_value, traceback)
self.b.__exit__(self, exc_type, exc_value, traceback)
Run Code Online (Sandbox Code Playgroud)
我能做到这一点,而无需手动调用__exit__上a和b?我什至__exit__正确调用吗?
假设我拥有的资源file不像示例中那样,并且没有像closeor那样的方法destroy。在__enter__and之上实现这样的方法可能是一种好习惯__exit__吗?
正如我在评论中提到的:
我认为这里最有帮助的是:
contextlib.ExitStack
您可以创建此对象作为__init__. 然后将所有依赖的 contextmanager 添加到其中,其中enter_context(cm)cm是context_manager
def __init__(self):
self.exit_stack = contextlib.ExitStack()
self.exit_stack.__enter__()
self.exit_stack.enter_context(open('foo'))
....
Run Code Online (Sandbox Code Playgroud)
要清除所有依赖的上下文,只需调用__exit__该堆栈的退出即可。
或者更好的是只是子类ExitStack并在 init 中调用enter_context.