为什么TemporaryDirectory在“with”块内改变类型?
在python3控制台中
>>> x1=tempfile.TemporaryDirectory()
>>> print(type(x1))
<class 'tempfile.TemporaryDirectory'>
>>> with tempfile.TemporaryDirectory() as x2:
... print(type(x2))
...
<class 'str'>
为什么x1
是TemporaryDirectory
类型,而x2
是str
类型呢?
1 个回答
3
因为 with foo() as x
这行代码会让 x
变成 foo().__enter__()
返回的值。
而 x = foo()
是另一回事。
你可以在 这里 查看 TemporaryDirectory
的实现;它做了很多事情,但最重要的是,进入上下文管理器时会返回目录的名称,而退出上下文管理器时会删除那个命名的目录。
class TemporaryDirectory:
...
def __enter__(self):
return self.name
...