动态创建变量名 [英] creating a variable name dynamically

查看:182
本文介绍了动态创建变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码来创建一个界面和一些按钮(maya中的python)

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)

我很难理解所有这些自我".工作流程,所以我可能缺少一些基本的知识,但到目前为止我尝试过的所有方法都无效:S

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

谢谢!

推荐答案

这只是一个语法问题.语法中指定的属性必须是标识符,如果要生成属性,则需要使用getattrsetattr(或delattr):

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)

用所需的值替换value.确实与self无关:self只是另一个函数参数,其行为与任何其他变量一样.

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.

这篇关于动态创建变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆