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