作者tsaiminghan (nahgnimiast)
看板Python
标题with和lock的用法?
时间Tue Dec 27 09:23:44 2022
因为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://webptt.com/cn.aspx?n=bbs/Python/M.1672104226.A.589.html
1F:→ robert09080: Context Manager 12/27 10:2:q
※ 编辑: tsaiminghan (101.12.47.188 台湾), 12/27/2022 16:17:35
2F:→ lycantrope: 这是python2.7吗 12/27 16:22
3F:→ tsaiminghan: python3 12/28 09:39