如何在代码中修改class对象参数

How to modify class object parameters in code

我想要完成的是在下面的示例中将 testobj.alpha 设置为 .5:

class test():
    def __init__(self):
        self.alpha = 0

d = {'alpha' : .5}
testobj = test()

for i in d:
    testobj.i = d[i] #creates a new class member called 'i' instead of setting alpha to .5

正如评论所说,在 for 循环中,创建了一个名为 i 的新 class 成员,而不是将现有的 alpha 成员设置为 .5

使用setattr动态设置属性:

for i in d:
    setattr(testobj, i, d[i])

或直接更新内部属性字典(vars will serve as a proxy for the __dict__ attribute):

vars(testobj).update(d) # No (explicit) loop

如果对象没有 __dict__ 属性(例如,它是用 __slots__ 属性定义的),后一种方法将失败。