调查 documentation python 中的 with 语句:
- 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“方法”。
