0

我正在尝试定义一个函数,该函数在我指定一个对象时返回一个列表,当我没有指定任何内容时,它会返回带有 *_control 的场景中所有对象的列表。这是我的函数,但它不起作用....我正在和玛雅一起工作..

from maya import cmds

def correct_value(selection):

       if not isinstance(selection, list):
            selection = [selection]
            objs = selection
            return objs

       if not selection : 
            objs = cmds.ls ('*_control')    
            return objs

当我没有指定任何内容时,它会返回一个错误:

错误:第 1 行:TypeError:文件第 1 行:correct_value() 正好采用 1 个参数(给定 0)

怎么了 ??

4

5 回答 5

2
def correct_value(selection=None):
     if selection is None:  # note that You should check this before  
                            # You wil check whether it is list or not
        objs = cmds.ls ('*_control')    
        return objs

    if not isinstance(selection, list):
        selection = [selection]
        objs = selection
        return objs
于 2013-06-05T13:27:41.287 回答
1

处理默认参数,即使它可能是None

def correct_value(*args):
    if not args:
        objs = cmds.ls ('*_control')    
        return objs
    elif len(args) == 1:
        selection = args
        objs = selection
        return objs
    else:
       raise TypeError # ...
于 2013-06-05T13:28:45.827 回答
1

Well, you wrote your function with a required argument. Therefore, you have to pass the argument. You can write it so the argument is optional by specifying the value that will be used when nothing is passed:

def correct_value(selection=None):

etc.

于 2013-06-05T13:18:46.663 回答
1

If you want a parameter to be optional, you need to provide a default value:

def correct_value(selection=None):
    # do something

    if selection is None: 
        #do something else
于 2013-06-05T13:19:03.060 回答
0

对于这类东西,这是一对非常有用的模式:

# always return a list from scene queries (maya will often return 'none' 
def get_items_named_foo():
     return cmds.ls("foo") or []  # this makes sure that you've always got a list, even if it's empty


# always use the variable *args method to pass in lists
def do_something(*args):
    for item in args:
        do_something(item)  # args will always be a tuple, so you can iterate over it

# this lets you do stuff like this without lots of boring argument checks:
do_something (*get_items_named_foo())

如果您始终使用这两种技巧,您可以透明地处理 Maya 查询返回 None 而不是列表的情况

顺便说一句,您可以模仿默认的 maya 行为(不传递参数使用当前选择),如下所示:

def work_on_list_or_selected(*args):
   args = args or cmds.ls(sl=True) or []
   for item in args:
       do_something (item)
于 2013-06-05T18:56:20.327 回答