Create a dynamic 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 rotate it to something like that to automatically create buttons and know their names (so I can request them later)

 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 am really having trouble understanding all of this self. workflow, so maybe I missed something basic, but everything I've tried so far has not worked: S

thanks!

+1
source share
2 answers

This is just a syntax issue. The attributes specified in the syntax must be identifiers, if you need the generated attributes, you need to use getattr or setattr (or delattr ):

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

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

+2
source

What about setattr ?

 class Foo: def __init__(self): # Set attribute "bar" on this object to the number 1 setattr(self, "bar", 1) 
+2
source

All Articles