小编Jea*_*ier的帖子

Python如何通过上下文管理器强制对象实例化?

我想通过类上下文管理器强制对象实例化。因此,使其无法直接实例化。

我实现了此解决方案,但从技术上讲,用户仍然可以实例化对象。

class HessioFile:
    """
    Represents a pyhessio file instance
    """
    def __init__(self, filename=None, from_context_manager=False):
        if not from_context_manager:
            raise HessioError('HessioFile can be only use with context manager')
Run Code Online (Sandbox Code Playgroud)

和上下文管理器:

@contextmanager
def open(filename):
    """
    ...
    """
    hessfile = HessioFile(filename, from_context_manager=True)
Run Code Online (Sandbox Code Playgroud)

有更好的解决方案吗?

python contextmanager

5
推荐指数
2
解决办法
583
查看次数

标签 统计

contextmanager ×1

python ×1