Python set属性等于另一个属性

时间:2018-06-18 13:19:19

标签: python

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

SIGKILL

预期结果:

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 = ...

3 个答案:

答案 0 :(得分:3)

你可以使用对象的__dict__或@bla setattr所说的 和Enum所以你不要使用字符串来指定属性:

from enum import Enum

class MyObject(object):
    def __init__(self):
        self.var_1 = 1
        self.var_2 = 2
        self.var_3 = 3
        self.current_var = None
    def update_var(self, value):
        if self.current_var is None:
            raise Exception('Current var is not set')
        self.__dict__[self.current_var.name] = value
        setattr(self, self.current_var.name, value) # Same result

m = MyObject()

attrs = vars(m)
attrs_enum = Enum("attrs_enum", attrs)


m.var_1 # 1
m.current_var = attrs_enum.var_1
m.update_var(10)
m.var_1 # 10

m.current_var = attrs_enum.var_2
m.var_2 # 2
m.update_var(20)
m.var_2 # 20

我不喜欢使用字符串来指定属性,但这是解决方案

答案 1 :(得分:1)

我建议将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)

实施例

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

答案 2 :(得分:0)

您可以为MyObject属性值创建包装类。这样,从current_var的内容到__dict__中绑定的属性将存在引用:

class _int:
   def __init__(self, _val):
     self.value = _val
   def __repr__(self):
     return str(self.value)

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

x = MyObject()
x.update_var(10)
print(x.var_1)
x.current_var = x.var_2
x.update_var(5)
print(x.var_2)

输出:

10
5