您也可以使用__enter__
and本地执行此操作__exit__
。简单的例子:
class SomeObject(object):
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
class Temporary(object):
def __init__(self, target, **kv):
self.target = target
self.to_set = kv
self.to_restore = {}
def __enter__(self):
self.to_restore = map(partial(getattr, self.target), filter(partial(hasattr, self.target), self.to_set.keys()))
for k,v in self.to_set.items():
if hasattr(self.target, k):
self.to_restore[k] = getattr(self.target, k)
setattr(self.target, k, v)
def __exit__(self, *_):
for k,v in self.to_restore.items():
setattr(self.target, k, v)
for k in self.to_set.keys():
if k not in self.to_restore:
delattr(self.target, k)
o = SomeObject()
print(o.__dict__)
with Temporary(o, a=42, d=1337):
print(o.__dict__)
print(o.__dict__)