Skip to main content
 首页 » 编程设计

python之用来自单个类中的 2 个类的语句包装 python

2025年05月04日19cloudgamer

我有一个带有 with 语句的 python 类 A 和带有 with 语句的 B 类。现在它的工作方式如下:

with A() as a: 
    with B() as b: 
        do_things() 

如何构建一个包含 A 类和 B 类的 C 类,以便我可以这样调用它:

 with C() as c: 
        do_things() 

具有相同的功能

请您参考如下方法:

我想推荐一个替代方案。您可以在同一行初始化 a 和 b:

with A() as a, B() as b: 
    do_things() 

这样更简洁并且减少了深度嵌套代码中的缩进量。

但是,如果您绝对必须使用一个类,则重写 __enter__ 和 __exit__ 方法:

class C: 
    def __enter__(self): 
        self._a = A() 
        self._b = B() 
        return (self._a.__enter__(), self._b.__enter__()) 
 
    def __exit__(self ,type, value, traceback): 
        # Cleanup code here. 
        self._b.__exit__(type, value, traceback) 
        self._a.__exit__(type, value, traceback) 

然后像这样在上下文管理器中使用 C:

with C() as (a, b): 
    do_things() 

如果您不想引用 a 和 b,或者您不打算对它们做任何事情,那么

with C(): 
    do_things() 

也会起作用。这应该足以开始,但请注意用户在评论中提到的缺点。主要是如果 self._b.__enter__ 抛出错误,self._a.__enter__ 将需要清理(这可以使用 try-except-finally 完成).此外,某些上下文管理器可能需要根据所管理的资源进行区别对待。