with和lock的用法?

作者: tsaiminghan (tsaiminghan)   2022-12-27 09:23:44
因為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
=====================
有版友可以解譯這個關係嗎?
作者: robert09080 (Aspettarei)   2022-12-27 10:27:00
Context Manager
作者: lycantrope (阿寬)   2022-12-27 16:22:00
這是python2.7嗎
作者: tsaiminghan (tsaiminghan)   2022-12-28 09:39:00
python3

Links booklink

Contact Us: admin [ a t ] ucptt.com