如何检查是否使用`with`语句创建对象?

发布于 2021-01-29 15:59:52

我想确保仅在“ with”语句中实例化该类。

即这是可以的:

with X() as x:
 ...

这不是:

x = X()

如何确保此类功能?

关注者
0
被浏览
42
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    到目前为止,所有答案都没有提供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()使用情况管理器时。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看