1 #try except finally 2 def exe_try(): 3 try: 4 print ("code started") 5 raise KeyError 6 return 1 7 except KeyError as e: 8 print ("key error") 9 return 2 10 else: 11 print ("other error") 12 return 3 13 finally: 14 print ("finally") 15 # return 4 16 17 #上下文管理器协议 18 class Sample: 19 def __enter__(self): 20 print ("enter") 21 #获取资源 22 return self 23 def __exit__(self, exc_type, exc_val, exc_tb): 24 #释放资源 25 print ("exit") 26 def do_something(self): 27 print ("doing something") 28 29 with Sample() as sample: 30 sample.do_something() 31 32 # if __name__ == "__main__": 33 # result = exe_try() 34 # print (result)
1 import contextlib 2 3 @contextlib.contextmanager 4 def file_open(file_name): 5 print ("file open") 6 yield {} 7 print ("file end") 8 9 with file_open("bobby.txt") as f_opened: 10 print ("file processing")
本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/articles/9368907.html