gpt4 book ai didi

python - python中上下文管理器的目的是什么

转载 作者:太空狗 更新时间:2023-10-29 22:15:21 26 4
gpt4 key购买 nike

<分区>

我正在阅读 http://eigenhombre.com/2013/04/20/introduction-to-context-managers/ .

其中:

Context managers are a way of allocating and releasing some sort of resource exactly where you need it. The simplest example is file access:

with file("/tmp/foo", "w") as foo:
print >> foo, "Hello!"

This is essentially equivalent to:

foo = file("/tmp/foo", "w")
try:
print >> foo, "Hello!"
finally:
foo.close()

这篇文章继续进行了更多解释,但我仍然不确定我是否简单地理解了它们的目的。有人可以澄清一下。还有什么是“上下文”?

我看过Trying to understand python with statement and context managers ,但我还是不确定上下文管理器的目的是什么?它只是“try..finally..”的替代语法还是其他目的

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