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")

 

相关文章:

  • 2021-06-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-12
猜你喜欢
  • 2021-07-12
  • 2021-07-24
  • 2021-06-09
  • 2021-08-12
  • 2022-02-08
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案