到目前为止,所有答案都没有提供OP 直接 想要的(我认为)。
(我认为)OP希望这样:
>>> with X() as x: ... # ok>>> x = X() # ERRORTraceback (most recent call last): File "run.py", line 18, in <module> x = X() File "run.py", line 9, in __init__ raise Exception("Should only be used with `with`")Exception: Should only be used with `with`
这是我想出的,可能不是很可靠,但我认为它最接近OP的意图。
import inspectimport linecacheclass X(): def __init__(self): if not linecache.getline(__file__, inspect.getlineno(inspect.currentframe().f_back) ).startswith("with "): raise Exception("Should only be used with `with`") def __enter__(self): return self def __exit__(self, *exc_info): pass
这将给完全相同的输出如我上面显示,只要
with是与同一线路
X()使用情况管理器时。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)