python——上下文管理器
####基于生成器实现的上下文管理器
from contextlib import contextmanager
#生成器
@contextmanager
def file_manager(name,mode):
try:
f = open(name,mode,encoding="utf-8")#打开文件
yield f#生成器
finally:
f.close()
with file_manager("1.txt","w") as f:
f.write("hello world")
####基于类实现的上下文管理器
class FKResouce:
def __init__(self,tag):
self.tag = tag
print("构造器,初始化资源:%s" % tag)
def __enter__(self):
print('[__enter__%s]:' % self.tag)
#返回值作为as字句中变量
return 'fkit'
def __exit__(self,exc_type,exc_value,exc_traceback):
print('[__exit__%s]:' % self.tag)
#exc_traceback为None,代表无异常
if exc_traceback is None:
print("没有异常时关闭资源")
else:
print("遇到异常时关闭资源")
return False
with FKResouce('孙武') as dr:
print(dr)
print('[with代码块],无异常')
print("__________________________")
with FKResouce("ha"):
print("[with代码块]异常之前的代码")
raise Exception
print("异常之后的代码")
还没有评论,来说两句吧...