本文最后更新于 2022-05-26 11:25:30
With
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class ContextMgr : def __enter__(self): print("调用enter 方法") return self
def __exit__(self, exc_type, exc_val, exc_tb): print("调用exit方法") print(exc_type) print(exc_val) print(exc_tb)
def myfunc(self): print("调用myfunc") return "aaaaa"
mgr = ContextMgr() mgr.myfunc()
with ContextMgr() as mgr2: print(mgr2.myfunc())
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class ContextMgr : def __enter__(self): print("调用enter 方法") return self
def __exit__(self, exc_type, exc_val, exc_tb): print("调用exit方法") print(exc_type) print(exc_val) print(exc_tb)
def myfunc(self): print("调用myfunc") return "aaaaa"
mgr = ContextMgr() mgr.myfunc()
with ContextMgr() as mgr2: print(mgr2.myfunc()) raise Exception("exc")
|
15with
https://jiajun.xyz/2020/11/02/python/01base/15with/