gpt4 book ai didi

python - 在 `variable` 中分配给 `with expression as variable` 的是什么?

转载 作者:太空狗 更新时间:2023-10-29 20:38:29 25 4
gpt4 key购买 nike

来自学习 Python:

The basic format of the with statement looks like this, with an optional part in square brackets here:

with expression [as variable]:
with-block

The expression here is assumed to return an object that supports the context management protocol (more on this protocol in a moment). This object may also return a value that will be assigned to the name variable if the optional as clause is present.

Note that the variable is not necessarily assigned the result of the expression; the result of the expression is the object that supports the context protocol, and the variable may be assigned something else intended to be used inside the statement.

expression 被评估为上下文管理器对象。

分配给变量的是什么?引用仅表示它不是上下文管理器对象。

variable 的赋值是否调用上下文管理器类的某些方法来生成分配给 variable 的实际值?

谢谢。

最佳答案

无论从 __enter__ 返回什么。来自documentation on the __enter__ method of context managers :

contextmanager.__enter__()

Enter the runtime context and return either this object or another object related to the runtime context. The value returned by this method is bound to the identifier in the as clause of with statements using this context manager.

(强调我的)

调用 __enter__ 的结果很可能是一个上下文管理器,规范中没有任何内容禁止这样做。正如文档所述,它当然可以是与运行时上下文相关的另一个对象。

__enter__ 返回自身的对象可以一次又一次地用作上下文管理器。 file objects ,例如:

with open('test_file') as f1:   # file.__enter__ returns self
with f1 as f2: # use it again, get __self__ back
print("Super context managing")
with f2 as f3, f1 as f4: # getting weird.
print("This can go on since f1.__enter__ returns f1")
print("f1.__exit__ has been called here, though :)")
print("f1 closed: {}".format(f1.closed))

并不是说前面的内容有多大意义,只是为了说明这一点。

关于python - 在 `variable` 中分配给 `with expression as variable` 的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46225193/

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