Python set属性等于另一个属性

bdo*_*leu 5 python

是否可以将类属性定位到同一对象的另一个属性,并具有更新目标值的功能?

class MyObject(object):
    def __init__(self):
        self.var_1 = 1
        self.var_2 = 2
        self.var_3 = 3
        self.current_var = self.var_1

    def update_var(self, value):
        self.current_var = ...
Run Code Online (Sandbox Code Playgroud)

预期结果:

>>> x = MyObject()
>>> x.update_var(10)
>>> x.var_1
10
>>> x.current_var = x.var_2
>>> x.update_var(5)
>>> x.var_2
5
Run Code Online (Sandbox Code Playgroud)

Oli*_*çon 2

我建议创建current_var一个充当给定实例属性的代理的属性。您可以用来set_current_var更新代理目标。

代码

class MyObject(object):
    current_var = 1
    def __init__(self):
        self.var_1 = 1
        self.var_2 = 2
        self.var_3 = 3

    def set_current_var(self, name):
        self._current_var = name

    @property
    def current_var(self):
        return getattr(self, self._current_var)

    @current_var.setter
    def current_var(self, value):
        setattr(self, self._current_var, value)
Run Code Online (Sandbox Code Playgroud)

例子

x = MyObject()

print(x.var_1) # 1

x.set_current_var('var_1')

print(x.current_var) # 1

x.current_var = 4

print(x.var_1) # 4
Run Code Online (Sandbox Code Playgroud)