小编iga*_*gal的帖子

Python TemporaryDirectory 在“with”语句中使用时返回字符串

Python TemporaryDirectory 在“with”语句中使用时返回字符串

问题的简短版本

为什么在上下文TemporaryDirectory中使用时返回字符串with

问题的较长版本

下面是一些 Python 代码的示例,它创建一个临时目录tempdir并打印相应的对象:

>>> import tempfile
>>> tempdir = tempfile.TemporaryDirectory(dir="/tmp")
>>> print(tempdir)
<TemporaryDirectory '/tmp/tmpf2yh8xu9'>

>>> print(type(tempdir))
<class 'tempfile.TemporaryDirectory'>
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,tempdir是 的一个实例TemporaryDirectory

这是一个类似的例子,我with在调用时使用了一个语句TemporaryDirectory

>>> import tempfile
>>> with tempfile.TemporaryDirectory(dir="/tmp") as tempdir: print(tempdir)
/tmp/tmp7mlmzegs

>>> with tempfile.TemporaryDirectory(dir="/tmp") as tempdir: print(type(tempdir))
<class 'str'>
Run Code Online (Sandbox Code Playgroud)

在本例中,tempdir是一个字符串。当我查看__enter__该类的方法时TemporaryDirectory,我看到以下内容:

def __enter__(self):
    return self.name
Run Code Online (Sandbox Code Playgroud)

果然 - 看起来返回的是一个字符串而不是对象本身。

造成这种差异的原因是什么?为什么该__enter__方法返回文件名而不是文件对象?

python python-3.x

8
推荐指数
1
解决办法
6292
查看次数

标签 统计

python ×1

python-3.x ×1