和裝飾器相似,都是包裝其餘代碼的工具。函數
裝飾器主要用於包裝代碼塊(函數或類(類方法)),而上下文管理器能夠包裝任何格式的代碼塊。工具
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__