gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:39:24 24 4
gpt4 key购买 nike

在一个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_methodwith ... as 范围内的 first_method 调用,所以我确定another_method 将在 first_method 退出 with ... as 范围之前完成 - 它有效。但是,我对这一行感到困惑:

self.output = f

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

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

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

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

最佳答案

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

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

关于python - 将 with ... as 语句的结果分配给 self.bar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46986856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com