我经常发现我需要临时分配一些成员变量,例如
old_x = c.x
old_y = c.y
# keep c.z unchanged
c.x = new_x
c.y = new_y
do_something(c)
c.x = old_x
c.y = old_y
但我希望我可以简单地写
with c.x = new_x; c.y = new_y:
do_something(c)
甚至
do_something(c with x = new_x; y = new_y)
Python 的装饰器或其他语言特性可以实现这种模式吗? (我可以根据需要修改
c
的类) 最佳答案
Context managers 可以很容易地使用它。
引用官方文档:
似乎保存和恢复状态正是我们想要在这里做的。
例子:
from contextlib import contextmanager
@contextmanager
def temporary_change_attributes(something, **kwargs):
previous_values = {k: getattr(something, k) for k in kwargs}
for k, v in kwargs.items():
setattr(something, k, v)
try:
yield
finally:
for k, v in previous_values.items():
setattr(something, k, v)
class Something(object):
def __init__(self, x, y):
self.x = x
self.y = y
def say_hello(self):
print("hello", self.x, self.y)
s = Something(1, 2)
s.say_hello() # hello 1 2
with temporary_change_attributes(s, x=4, y=5):
s.say_hello() # hello 4 5
s.say_hello() # hello 1 2
关于python - 如何临时分配成员变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38531851/