如何暂时分配成员变量?

时间:2016-07-22 17:02:29

标签: python python-2.7 python-decorators python-descriptors

我经常发现我需要临时分配一些成员变量,例如

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的课程)

5 个答案:

答案 0 :(得分:20)

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

答案 1 :(得分:5)

我认为contextmanager应该做你想做的事情:

from contextlib import contextmanager

@contextmanager
def current_instance(c, temp_x, temp_y):
    old_x, old_y = c.x, c.y
    c.x, c.y = temp_x, temp_y
    yield c
    c.x, c.y = old_x, old_y

with current_instance(c, x, y) as c_temp:
    do_something(c_temp) 

答案 2 :(得分:3)

mock提供此功能,特别是the docs for that function的上下文管理器用法。它位于python3的核心库中,而patch.object适用于较旧的python。

设定:

>>> class C:
...     def __init__(self, x, y, z):
...         self.x = x
...         self.y = y
...         self.z = z
...         
>>> c = C(0,1,2)

用法演示:

>>> print(c.x, c.y, c.z)
0 1 2
>>> with patch.object(c, 'x', 'spam'), patch.object(c, 'y', 'eggs'):
...     print(c.x, c.y, c.z)
...     
spam eggs 2
>>> print(c.x, c.y, c.z)
0 1 2

答案 3 :(得分:3)

您也可以使用__enter____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__)

答案 4 :(得分:2)

高飞解决方案

>>> class Foo(object):
        def __init__(self):
             self._x = []
             self._y = []


        @property
        def x(self):
           return self._x[-1] or None

        @x.setter 
        def x(self, val):
           self._x.append(val)

        def reset_vals(self):
           if len(self._x) > 1:
              self._x.pop()


>>> bar = Foo()
>>> bar.x = 1
>>> bar.x
1
>>> bar.x = 2
>>> bar.x
2
>>> bar.reset_vals()
>>> bar.x
1
>>> bar.reset_vals()
>>> bar.x
1

仍然愚蠢但不那么解决方案

>>> class Foo(object):
    def __init__(self):
        pass


>>> import copy
>>> bar = Foo()
>>> bar.x = 1
>>> bar.x
1
>>> bar2 = copy.copy(bar)
>>> bar2.x
1
>>> bar2.x = 5
>>> bar2.x
5
>>> bar
<__main__.Foo object at 0x0426A870>
>>> bar.x
1