[英]Creating variable names dynamically from list
So I'm getting into using the Python API in maya and some tools require me to iterate code over various objects. 因此,我开始在Maya中使用Python API,并且一些工具要求我遍历各种对象上的代码。 This requires attaching an object reference with it's name to an object creator's output, and then running a function immediately after it's called.
这需要将具有其名称的对象引用附加到对象创建者的输出,然后在调用它后立即运行一个函数。
Rather than running (hypothetical example): 而不是运行(一个假设的示例):
className.myObject1 = mayaClass.create(myObject1)
func1()
func2()
className.myObject2 = mayaClass.create(myObject2)
func1()
func2()
etc.. 等等..
is there a way I could say do this: 有没有办法我可以说做到这一点:
myObjs = ['myObject1','myObject2','myObject3']
for obj in myObjs:
className.obj = mayaClass.create(obj)
func1()
func2()
It would certainly save a lot of typing, shrink down the script size and make things more easily maintainable. 当然,这样可以节省大量的键入时间,缩小脚本的大小,并使事情更易于维护。
The function assigns the value to the attribute, provided the object allows it.
如果对象允许,该函数将值分配给属性。 For example,
setattr(x, 'foobar', 123)
is equivalent tox.foobar = 123
.例如,
setattr(x, 'foobar', 123)
等效于x.foobar = 123
。
setattr()
will set a object's attribute (given by a string) to the specified value setattr()
会将对象的属性(由字符串赋予)设置为指定值
vars()
will get the local variables as a dictionary vars()
将获取本地变量作为字典
Have a look at http://docs.python.org/library/functions.html for important builtins of Python 看看http://docs.python.org/library/functions.html ,了解Python的重要内建函数
myObjs = ['myObject1','myObject2','myObject3']
for obj in myObjs:
setattr(className, obj, mayaClass.create(vars()[objs]))
func1()
func2()
EDIT: I noticed also another answer mentions exec
. 编辑:我注意到另一个答案提到了
exec
。 Be careful when using this in any python code . 在任何python代码中使用此代码时都要小心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.