gpt4 book ai didi

python - 文件对象 __exit__() 方法的文档

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

调查 documentation python 中的 with 语句:

  1. The context manager’s __exit__() method is invoked.

我想知道如果我这样做会发生什么

with open("foo","w") as f:
pass

从文档和评估为 True 的 f.closed 来看,__exit__() 似乎有点等同于 close()。但我想知道是否可以找到有关 __exit__() 函数实际行为的更多详细信息。任何提示表示赞赏。

最佳答案

作为更具体的答案,open 返回 _io._IOBase 的子类(取决于选项)。 __exit__ 方法在 iobase.c 中用 C 语言实现用代码

static PyObject *
iobase_exit(PyObject *self, PyObject *args)
{
return PyObject_CallMethodObjArgs(self, _PyIO_str_close, NULL);
}

您可以看到,只是调用对象close“方法”。

关于python - 文件对象 __exit__() 方法的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48442482/

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