看板 Python 關於我們 聯絡資訊
因為threading Lock是built in,所以沒有辦法繼承 所以模擬一下 ==================== from threading import Lock class Wlock(object): def __init__(self): self.lock = Lock() for attr in dir(self.lock): self.__dict__[attr] = getattr(self.lock, attr) with A(): pass ==================== 錯誤訊息如下 with a: AttributeError: __enter__ 怎麼樣的東西才算是attr?因為A().__dict__裡面有__enter__ 但是with卻抓不到。 還是__dict__里面的東西不算attribute,一定要原來有的才算? 承上,Wlock補上下面2個函式後,雖然實際沒被呼叫到,但就可以用with。 ==================== def __enter__(self): raise NotImplementedError def __exit__(self, type, value, trace): raise NotImplementedError ===================== 有版友可以解譯這個關係嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 101.12.47.188 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1672104226.A.589.html
robert09080: Context Manager 12/27 10:2:q
※ 編輯: tsaiminghan (101.12.47.188 臺灣), 12/27/2022 16:17:35
lycantrope: 這是python2.7嗎 12/27 16:22
tsaiminghan: python3 12/28 09:39