with和lock的用法?
看板Python作者tsaiminghan (nahgnimiast)時間2年前發表 (2022/12/27 01:23), 2年前編輯推噓0(0推 0噓 3→)留言3則, 3人參與, 2年前最新討論串1/1
因為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
→
12/27 10:2:q, , 1F
12/27 10:2:q, 1F
※ 編輯: tsaiminghan (101.12.47.188 臺灣), 12/27/2022 16:17:35
→
12/27 16:22,
2年前
, 2F
12/27 16:22, 2F
→
12/28 09:39,
2年前
, 3F
12/28 09:39, 3F
Python 近期熱門文章
PTT數位生活區 即時熱門文章