Skip to main content
 首页 » 编程设计

python之如何访问上下文管理器的属性

2025年05月04日33lyj

我想完成类似的事情:

class my_context(object): 
    def __init__(self): 
        self.obj1 = Obj() 
        self.obj2 = Obj() 
        ... 
 
    def __enter__(self): 
        ''' initialize objects ''' 
 
    def __exit__(self, type, value, tb): 
        ''' uninitialize objects ''' 

有许多Obj 属性是需要关闭/删除/等等的资源。我希望使用上下文管理器来设置它们,然后摆脱它们。但是我发现我在尝试时无法访问这些属性:

with my_context() as cont: 
    cont.obj1  # doesn't work 

有什么方法可以访问这些属性?

请您参考如下方法:

要使 with...as 语法正常工作,您的 __enter__() 必须返回一个值。

如果你想使用与你的 my_context 类提供的相同的属性,你可能想要返回 self。