使用一个函数更新不同的类属性

时间:2018-08-14 16:18:14

标签: python python-3.x class parameters

在模块中,如果需要,我想问一个类的实例来更新类属性。这是代码示例:

class ExampleClass:

    def __init__(self):
        self.data1 = None
        self.data2 = None
        self.data3 = None

    def updateData1(self, withInfo):
        self.dataUpdater(self.data1, withInfo)

    def updateData2(self, withInfo):
        self.dataUpdater(self.data2, withInfo)

    def updateData3(self, withInfo):
        self.dataUpdater(self.data3, withInfo)

    def dataUpdater(self, data, withInfo):
        # Very long and complex class function.
        # I would like to keep this logic in one function instead of making copies of it.
        data = 'new data'

但是当更新数据时,我尝试在另一个模块中获取该特定数据时,它仍然是None。现在我了解发生了什么。我基本上是在dataUpdater的{​​{1}}中重写并制作一个新变量。而且我的特定类属性永远不会更新。我的问题是如何更新传入的数据(特定的类属性)?

我花了半天的时间来解决这个问题,但似乎找不到我想要的东西。

2 个答案:

答案 0 :(得分:2)

您可以尝试使用setattr设置要更新的属性。即

Class ExampleClass:

def __init__(self):
    self.data1 = None
    self.data2 = None
    self.data3 = None

def updateData1(self, withInfo):
    self.dataUpdater('data1', withInfo)

def updateData2(self, withInfo):
    self.dataUpdater('data2', withInfo)

def updateData3(self, withInfo):
    self.dataUpdater('data3', withInfo)

def dataUpdater(self, attr_name, withInfo):
    # Very long and complex class function.
    # I would like to keep this logic in one function instead of making copies of it.
    setattr(self, attr_name, 'new_data')

答案 1 :(得分:1)

您尝试通过引用传递self.data#变量,这在Python中像C这样的语言中不能轻松控制。如果您想保留类似的实现,请考虑为对象使用数组,并传递值的索引以更新为dataUpdater方法。

相关问题