小编Len*_*ger的帖子

我可以从python上下文管理器中检索__exit__的返回值吗?

我在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
Run Code Online (Sandbox Code Playgroud)

因此,如何访问__exit__with块之后(或末尾)返回的my_results 。在该__exit__方法中返回其他True甚至合法吗?

python with-statement contextmanager

1
推荐指数
1
解决办法
978
查看次数

标签 统计

contextmanager ×1

python ×1

with-statement ×1