Skip to main content
 首页 » 编程设计

python之将 with ... as 语句的结果分配给 self.bar

2024年10月01日6kuangbin

在一个Python类中,一个方法打开了一个文件,但实际使用文件对象的是另一个方法。所以我写:

def first_method(self): 
    with open(FILE) as f: 
        self.output = f 
        self.another_method() 
 
def another_method(self): 
    self.output.write(DATA) 

如您所见,another_method 由 with ... as 范围内的 first_method 调用,所以我确定another_method 将在 first_method 退出 with ... as 范围之前完成 - 它有效。但是,我对这一行感到困惑:

self.output = f 

在另一个函数中使用 with ... as 语句的结果是好的做法吗?这会导致意外或无法控制的行为吗?

而且,another_method 并不是唯一使用 f 的地方。实际上,another_method 是一个协程,其中很多会异步写入f。所以我必须在 another_method 之外打开文件。

还有许多其他上下文管理器面临同样的问题,例如 aiohttp.ClientSession、tqdm.tqdm。将它们作为参数传递会导致参数过多。

其实问题是在我写this的时候出现的.

请您参考如下方法:

with 语句导致在 block 的末尾自动执行对象的 __exit__ 方法。假设在 __exit__ 之后对象处于不可用状态是合理的,即使您仍然有对它的引用。将其保存为对象属性是不明智的。

在您的具体示例中,您最好将文件作为参数显式传递给 another_method。