在 Python 中应该如何处理在另一个上下文管理器中创建的上下文管理器?
示例:假设您有A
充当上下文管理器的类,以及B
还充当上下文管理器的类。但是类B
实例必须实例化并使用类的实例A
。我已经完成了 PEP 343,这是我想到的解决方案:
class A(object):
def __enter__(self):
# Acquire some resources here
return self
def __exit__(seplf, exception_type, exception, traceback):
# Release the resources and clean up
pass
class B(object):
def __init__(self):
self.a = A()
def __enter__(self):
# Acquire some resources, but also need to "start" our instance of A
self.a.__enter__()
return self
def __exit__(self, exception_type, exception, traceback):
# Release the resources, and make our instance of A clean up as well
self.a.__exit__(exception_type, exception, traceback)
这是正确的方法吗?还是我错过了一些陷阱?