为什么TemporaryDirectory在“with”块内改变类型?

-5 投票
1 回答
53 浏览
提问于 2025-04-13 13:10

在python3控制台中

>>> x1=tempfile.TemporaryDirectory()
>>> print(type(x1))
<class 'tempfile.TemporaryDirectory'>
>>> with tempfile.TemporaryDirectory() as x2:
...   print(type(x2))
... 
<class 'str'>

为什么x1TemporaryDirectory类型,而x2str类型呢?

1 个回答

3

因为 with foo() as x 这行代码会让 x 变成 foo().__enter__() 返回的值。

x = foo() 是另一回事。

你可以在 这里 查看 TemporaryDirectory 的实现;它做了很多事情,但最重要的是,进入上下文管理器时会返回目录的名称,而退出上下文管理器时会删除那个命名的目录。

class TemporaryDirectory:
   ...

    def __enter__(self):
        return self.name

   ...

撰写回答