creating a variable name dynamically
我有这个代码来创建一个接口和一些按钮(玛雅语中的python)
1 2 3 4 5 6 7 8 9 10 11 12 13 | class mrShadowMapChangerUI: def __init__(self): smAttrs = ['shadowMap','smapResolution','smapSamples','smapSoftness','smapBias'] smNiceAttrs = ['Active','Resolution','Samples','Softness','Bias'] attrs = zip(smAttrs,smNiceAttrs) self.form = mc.columnLayout() self.smapResolutionField = mc.textFieldButtonGrp( label=attrs[1][1], text=int(defaultLightValues[1]), bc=Callback(self.setSmValue, attrs[1][0])) self.smapSamplesField = mc.textFieldButtonGrp( label=attrs[2][1], text=int(defaultLightValues[2]), bc=Callback(self.setSmValue, attrs[2][0])) self.smapSoftnessField = mc.textFieldButtonGrp( label=attrs[3][1], text=('%.3f' % defaultLightValues[3]), bc=Callback(self.setSmValue, attrs[3][0])) self.smapBiasField = mc.textFieldButtonGrp( label=attrs[4][1], text=('%.3f' % defaultLightValues[4]), bc=Callback(self.setSmValue, attrs[4][0])) |
我想把它变成这样,自动创建按钮并知道它们的名称(这样我以后可以查询它们)。
1 2 3 4 5 6 7 8 9 10 11 12 | class mrShadowMapChangerUI: def __init__(self): smAttrs = ['shadowMap','smapResolution','smapSamples','smapSoftness','smapBias'] smNiceAttrs = ['Active','Resolution','Samples','Softness','Bias'] attrs = zip(smAttrs,smNiceAttrs) self.form = mc.columnLayout() for attr in attrs: self.('%s' % attr[0]) = mc.textFieldButtonGrp( label=attr[1], text=int(defaultLightValues[1]), bc=Callback(self.setSmValue, attr[0])) mc.showWindow(self.window) |
号
我真的很难理解所有这些"自我"的工作流程,所以我可能遗漏了一些基本的东西,但是直到现在我所做的一切都没有起作用:s
谢谢!
埃多克斯1〔1〕怎么样?
1 2 3 4 | class Foo: def __init__(self): # Set attribute"bar" on this object to the number 1 setattr(self,"bar", 1) |
号
这只是一个语法问题。语法中指定的属性必须是标识符,如果需要生成的属性,则需要使用
1 2 | for attr, nice in zip(attrs, niceAttrs): setattr(self, attr, value) |
将