Search code examples
pythonvariablesobjectselfmaya

creating a variable name dynamically


I have this code to create an interface and some buttons (python in maya)

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]))

and I would like to turn it to something like this to create the buttons automatically and knowing their names (so I can query them later on)

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)

I'm really having troubles in understanding all this "self." workflow, so probably I'm missing something basic but all what I've tried until now has not worked :S

thanks!


Solution

  • It's just a syntax problem. Attributes specified in syntax must be identifiers, if you want generated attributes you'll need to use getattr or setattr (or delattr):

    for attr, nice in zip(attrs, niceAttrs):
        setattr(self, attr, value)
    

    Replace value with the value you want. This really has nothing to do with self: self is just another function argument and behaves like any other variable.