什么时候可以考虑上下文管理器
当你的代码逻辑需要用到如下关键字时,可以考虑使用上下文管理器让你的代码更加优雅:
try:
...
finally:
...
接下来介绍实现上下文管理器的三种方法。
方法1(上下文管理器协议)
总所周知,open()是默认支持上下文管理器的。所以打开一个txt文件,并向里面写入内容,再关闭这个文件的代码可以这样写:
with open("1.txt", "w") as file:
file.write("this is a demo")
这是等同于:
file = None
try:
file = open("1.txt", "w")
file.write("this is a demo")
finally: