上下文管理器with

import queueimport contextlib#裝飾成上下文函數,上下文管理器@contextlib.contextmanagerdef worker_state(a1,a2):    a1.append(a2)#with後執行    try:        yield#回到執行語句,語句執行完畢後返回這裏    finally:        a1.remove(a2)#執行q = queue.Queue()q.put("123")a1 = []a2 = "456"with worker_state(a1,a2):    print(q.get())#自定義opendef myopen(file_path,mode):    f = open(file_path,mode,encoding="utf-8")    try:        yield f#返回f,操做完成後回到這個位置    finally:        f.close()#執行closewith myopen("1.txt","a") as f:    f.write()
相關文章
相關標籤/搜索