我正在尝试实现一个使用 python 上下文管理器的类..
虽然我理解 enter 和 exit 的一般概念,但我不知道如何在多个代码块中使用相同的上下文管理器。
以下例为例
@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 期间并使用相同的上下文管理器对象来执行我的所有操作,然后最后当对象被删除时我想进行恢复手术我该怎么办?
我应该手动调用 enter 和 exit 而不是使用 with 语句吗?
在
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()