我在Python中使用上下文管理器。我希望从我的
__exit__
方法中获取一些日志。因此,我的代码记录了如下内容:class MyContextManager:
def __init__(self, value1, value2)
self.value1 = value1
self.value2 = value2
def __enter__(self)
# Do some other stuff
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# Do some tear down action, process some data that is
# created in __enter__ and log those results
return my_results
with MyContextManager(value1=my_value1, value2=my_value2) as manager:
# Do some stuff
那么我怎么才能访问从 __exit__
返回的 my_results,在我的 with 语句块结束后(或在末尾)呢? 在 __exit__
方法中返回 True 以外的内容合法吗?