如何在不同的方法中使用相同的上下文管理器?

问题描述 投票:0回答:1

我正在尝试实现一个使用 python 上下文管理器的类..

虽然我理解 enterexit 的一般概念,但我不知道如何在多个代码块中使用相同的上下文管理器。

以下例为例

@contextmanager 
def backupContext(input)
   try:
     return xyz
   finally
     revert (xyz)

class do_something:

   def __init__(self):
         self.context = contextVal

   def doResourceOperation_1():
       with backupContext(self.context) as context:
           do_what_you_want_1(context)

   def doResourceOperation_2():
       with backupContext(self.context) as context:
         do_what_you_want_2(context)

我调用上下文管理器两次..假设我只想执行一次..在 init 期间并使用相同的上下文管理器对象来执行我的所有操作,然后最后当对象被删除时我想进行恢复手术我该怎么办?

我应该手动调用 enterexit 而不是使用 with 语句吗?

python-3.x contextmanager
1个回答
0
投票

with
方法内的
__init__
语句块中调用你想要的两个方法,如下所示:

@contextmanager 
def backupContext(input)
   try:
       return xyz
   finally:
       revert (xyz)
        
class DoSomething():
    def __init__(self, obj):
        self.obj = obj
        with backupContext(self.obj) as c:
            self.action1()
            self.action2()

    def action1(self):
        """ action 1"""
        pass

    def action2(self):
        """ action 2"""
        pass

或者,如果您确实想在对象被 deleted 时执行恢复操作,请使用带有

__del__
方法的类,而不是使用
@contextmanager
装饰器,如下所示:

class MyObject():
    def __init__(self):
        do_enter_action()
    def __del__(self):
        do_exit_action()
© www.soinside.com 2019 - 2024. All rights reserved.