上下文管理器-with
# with 我们称之为上下文管理器,很多需要手动关闭的链接
# 比如说文件链接,socket链接,数据库的链接,都能使用with关键字自动关闭链接
# with 关键字后面对象,需要实现__enter__和exit__魔法方法
# with 结合 open使用,可以帮助我们自动释放资源
代码示例
x = open("name.txt", encoding="utf8")
print(type(x))
try:
with open("name.txt", "r", encoding="utf8") as file:
file.read() # 不需要在手动关闭文件
# file.close() #with 关键字会帮助我们关闭文件
except Exception:
print("文件未找到")
with 原理
# 上下文管理器
# with 语句后面的结果对象需要重写__enter__和__exit__方法
# 当进入到with代码块时,会自动调用__enter__方法的代码
# 当with代码块执行完后后,会自动调用__exit__代码
class Demo(object):
def __enter__(self):
print("__enter__方法被执行了")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("__exit__方法被调用了")
y = create_obj()
d = y.__enter__()
# with Demo() as d: # as 变量名
# print(d)
# 变量 d 不是 create_obj的返回结果,
# 它是创建的对象x调用create_obj之后的返回结果