【发布时间】:2017-09-06 07:53:51
【问题描述】:
我在 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
那么我如何访问在我的 with 块之后(或末尾)从__exit__ 返回的 my_results。在 __exit__ 方法中返回 True 以外的内容是否合法?
【问题讨论】:
标签: python with-statement contextmanager