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

Jea*_*ier 5 python contextmanager

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

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

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)

有更好的解决方案吗?

cgl*_*cet 9

如果您认为您的客户将遵循基本的 Python 编码原则,那么您可以保证如果您不在上下文中,则不会调用您的类中的任何方法。

您的客户端不应该__enter__显式调用,因此如果__enter__被调用,您就知道您的客户端使用了一条with语句,因此在上下文中(__exit__将被调用)。

你只需要一个布尔变量来帮助你记住你是在上下文中还是在上下文之外。

class Obj:
    def __init__(self):
        self._inside_context = False

    def __enter__(self):
        self._inside_context = True
        print("Entering context.")
        return self

    def __exit__(self, *exc):
        print("Exiting context.")
        self._inside_context = False

    def some_stuff(self, name):
        if not self._inside_context:
            raise Exception("This method should be called from inside context.")
        print("Doing some stuff with", name)

    def some_other_stuff(self, name):
        if not self._inside_context:
            raise Exception("This method should be called from inside context.")
        print("Doing some other stuff with", name)


with Obj() as inst_a:
    inst_a.some_stuff("A")
    inst_a.some_other_stuff("A")

inst_b = Obj()
with inst_b:
    inst_b.some_stuff("B")
    inst_b.some_other_stuff("B")

inst_c = Obj()
try:
    inst_c.some_stuff("c")
except Exception:
    print("Instance C couldn't do stuff.")
try:
    inst_c.some_other_stuff("c")
except Exception:
    print("Instance C couldn't do some other stuff.")
Run Code Online (Sandbox Code Playgroud)

这将打印:

Entering context.
Doing some stuff with A
Doing some other stuff with A
Exiting context.
Entering context.
Doing some stuff with B
Doing some other stuff with B
Exiting context.
Instance C couldn't do stuff.
Instance C couldn't do some other stuff.
Run Code Online (Sandbox Code Playgroud)

由于您可能有许多要“保护”不被外部上下文调用的方法,因此您可以编写一个装饰器以避免重复相同的代码来测试您的布尔值:

def raise_if_outside_context(method):
    def decorator(self, *args, **kwargs):
        if not self._inside_context:
            raise Exception("This method should be called from inside context.")
        return method(self, *args, **kwargs)
    return decorator
Run Code Online (Sandbox Code Playgroud)

然后将您的方法更改为:

@raise_if_outside_context
def some_other_stuff(self, name):
    print("Doing some other stuff with", name)
Run Code Online (Sandbox Code Playgroud)


小智 5

我建议采用以下方法:

class MainClass:
    def __init__(self, *args, **kwargs):
        self._class = _MainClass(*args, **kwargs)

    def __enter__(self):
        print('entering...')
        return self._class

    def __exit__(self, exc_type, exc_val, exc_tb):
        # Teardown code
        print('running exit code...')
        pass


# This class should not be instantiated directly!!
class _MainClass:
    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2
        ...

    def method(self):
        # execute code
        if self.attribute1 == "error":
            raise Exception
        print(self.attribute1)
        print(self.attribute2)


with MainClass('attribute1', 'attribute2') as main_class:
    main_class.method()
print('---')
with MainClass('error', 'attribute2') as main_class:
    main_class.method()
Run Code Online (Sandbox Code Playgroud)

这将输出:

entering...
attribute1
attribute2
running exit code...
---
entering...
running exit code...
Traceback (most recent call last):
  File "scratch_6.py", line 34, in <module>
    main_class.method()
  File "scratch_6.py", line 25, in method
    raise Exception
Exception
Run Code Online (Sandbox Code Playgroud)