我正在尝试定义一个函数,当我指定一个对象时返回一个列表,当我没有指定任何东西时,它返回一个带有* _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() 只取一个参数(0给定)
怎么了?
答案 0 :(得分: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
答案 1 :(得分:1)
好吧,你用一个必需的参数编写了你的函数。因此,您必须传递参数。您可以编写它,以便通过指定传递任何内容时将使用的值来使参数成为可选参数:
def correct_value(selection=None):
等
答案 2 :(得分:1)
如果您希望参数是可选的,则需要提供默认值:
def correct_value(selection=None):
# do something
if selection is None:
#do something else
答案 3 :(得分: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 # ...
答案 4 :(得分: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查询返回的情况而不是列表
顺便说一下,你可以模仿默认的maya行为(传递没有参数使用当前选择的地方),如下所示:
def work_on_list_or_selected(*args):
args = args or cmds.ls(sl=True) or []
for item in args:
do_something (item)