和装饰器相似,都是包装其余代码的工具。函数
装饰器主要用于包装代码块(函数或类(类方法)),而上下文管理器能够包装任何格式的代码块。工具
1个关键字 with this
2个方法:enter,exitspa
使用情景1:it
with open(the_file) as f:io
f.read()ast
使用情景2:class
class contextManager:module
def __enter__(self):file
pass
def __exit__(self):
pass
condition1:
class contextManger2:
def __exit__(self,exc_type,exc_instance,traceback):
if not exc_type:
return True
elif exc_type == ValueError:
print("handing valueerror:%s" %exc_instance)
return True
else:
return False
with contextManger2 as c2:
raise ValueError("this is a error")
Traceback (most recent call last): File "D:\userdata\xiguan\workspace\practice\context.py", line 28, in <module> with contextManger2 as c2: AttributeError: __exit__