別のコンテキストマネージャー内で作成されたコンテキストマネージャーは、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)
これは正しいアプローチですか?それとも、いくつかの落とし穴がありませんか?