gpt4 book ai didi

python - 上下文管理器的 "opening work"应该发生在 __init__ 还是 __enter__ 中?

转载 作者:行者123 更新时间:2023-12-02 16:01:35 26 4
gpt4 key购买 nike

我找到了 following example File 对象的上下文管理器:

class File(object):
def __init__(self, file_name, method):
self.file_obj = open(file_name, method)
def __enter__(self):
return self.file_obj
def __exit__(self, type, value, traceback):
self.file_obj.close()

在这里,管理器完成的工作,即实际打开文件,发生在 __init__ 方法中。但是,在随附的文本中,他们建议文件打开应该发生在 __enter__ 调用中:

Let’s talk about what happens under-the-hood.

  1. The with statement stores the exit method of the File class.
  2. It calls the enter method of the File class.
  3. The enter method opens the file and returns it.
  4. The opened file handle is passed to opened_file.
  5. We write to the file using .write().
  6. The with statement calls the stored exit method.
  7. The exit method closes the file.

一般来说,哪种方法是正确的?似乎 __exit__ 撤消的工作应该发生在 __enter__ 中,而不是 __init__ 中,因为它们由上下文管理器机制 1:1 配对, 但这个例子让我怀疑。

最佳答案

没有统一的答案。这取决于工作是什么。例如,对于文件,打开发生在 __init__,但对于锁,锁定发生在 __enter__

要考虑的一件重要事情是,如果对象用作上下文管理器,或者不立即用作上下文管理器,应该发生什么?构造后对象的状态应该是什么?届时是否应该已经获得相关资源?

对于文件,答案是肯定的,文件应该已经打开,所以打开发生在__init__。对于锁,答案是否定的,锁不应该被锁定,所以锁定进入__enter__

另一件需要考虑的事情是,这个对象是否应该多次用作上下文管理器?如果两次进入上下文管理器应该做两次事情,那件事需要在 __enter__ 中发生。

关于python - 上下文管理器的 "opening work"应该发生在 __init__ 还是 __enter__ 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70546410/

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