我想确保仅在“ with”语句中实例化该类。
即这是可以的:
with X() as x:
...
这不是:
x = X()
如何确保此类功能?
到目前为止,所有答案都没有提供OP直接想要的(我认为)。
(我认为)OP希望这样:
>>> with X() as x:
... # ok
>>> x = X() # ERROR
Traceback (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 inspect
import linecache
class 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()
使用情况管理器时。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句