使用字典更改 python 中对应的 self 值的方法

Method which uses a dictionary to change a corresponding self value in python

如标题所示,我想创建一种方法,根据字典中的值更改自变量。这对我来说有点难以表达,所以让我们用下面的例子来说明:

class Foo:
    def __init__(self):
        self.bar = "something"
        self.baz = "something else"

    def change_a_value(self, new_value): #let's assume new_value is a list with the first item being the value we want to change, and the second being what we want to change it to.
        values = { "bar": self.bar, "baz": self.baz }
        values[new_value[0]] = new_value[1] # i want this to set self.bar to the second item in new_value

myClassInstance = Foo()
myClassInstance.change_a_value(["bar", "something new"])
print(myClassInstance.bar) # i want this to return 'something new', but it still returns 'something'

有没有可能做我想做的事?有没有更简单、更优雅的方法来做到这一点?我想避免为抽象目的创建像 change_barchange_baz 这样的函数,但如果这是最干净的方法,那没关系。

您需要 setattr 函数:

setattr(self, new_value[0], new_value[1])