函数在Python中是否可以为其参数使用双名?
我的意思是变量名的简短完整形式。
我会尝试更加清楚。每个熟悉Autodesk Maya的人都知道
进行约束的功能。它具有一些标志,您可以使用其名称的短或长格式:
maintainOffset(mo),weight(w),layer(l)等。
因此,您可以使用不同名称的参数来调用此函数,但它会为您提供相同的结果:
cmds.parentConstraint(driverObj, drivenObj, maintainOffset=True, weight=1.0,..)
cmds.parentConstraint(driverObj, drivenObj, maintainOffset=True, w=1.0,..)
cmds.parentConstraint(driverObj, drivenObj, mo=True, weight=1.0,..)
cmds.parentConstraint(driverObj, drivenObj, mo=True, w=True,..)
如何在Python 2.7.x中实现这种行为?我正在积极使用文档,但仍然找不到答案。
此外,我为各种约束定义了4个函数:
# Parent Constraint
def doParentConstraint(lst, mo = True, w = 1.0, sr = 'None', st = 'None', l = 'None'):
for pair in lst:
cmds.parentConstraint(pair[0], pair[1], maintainOffset = mo, weight = w,
skipRotate = sr, skipTranslate = st, layer = l)
# Orient Constraint
def doOrientConstraint(lst, mo = False, w = 1.0, o = (0.0, 0.0, 0.0), sk = 'None', l = 'None'):
for pair in lst:
cmds.orientConstraint(pair[0], pair[1], maintainOffset = mo, weight = w,
offset = o, skip = sk, layer = l)
# Point Constraint
def doPointConstraint(lst, mo = False, w = 1.0, o = (0.0, 0.0, 0.0), sk = 'None', l = 'None'):
for pair in lst:
cmds.orientConstraint(pair[0], pair[1], maintainOffset = mo, weight = w,
offset = o, skip = sk, layer = l)
# Scale Constraint
def doScaleConstraint(lst, mo = False, w = 1.0, o = (0.0, 0.0, 0.0), sk = 'None', l = 'None'):
for pair in lst:
cmds.orientConstraint(pair[0], pair[1], maintainOffset = mo, weight = w,
offset = o, skip = sk, layer = l)
连接列表:
cLst = produceConnectionList(tNodesA, tNodesB)
以及所有这些的某种包装函数:
def batchConnect(type = "parentConstraint", ???):
cLst = produceConnectionList(tNodesA, tNodesB)
if type is "parentConstraint": doParentConstraint(cLst, ???)
if type is "orientConstraint": doOrientConstraint(cLst, ???)
if type is "pointConstraint": doPointConstraint(cLst, ???)
if type is "scaleConstraint": doScaleConstraint(cLst, ???)
但是我不知道如何在这些函数和包装器之间传递值,因为尽管它们具有相同数量的参数,但是参数的名称和那些类型略有不同。
另外,我还想在调用包装器时使用标志名的短格式和完整格式:
batchConnect("pointConstraint", mo=False, offset=(0,0,0), weight=1)
batchConnect("pointConstraint", maintainOffset=False, o=(0,0,0), w=1)
必须做同样的事情。
batchConnect("pointConstraint")
如果没有参数,则必须使用默认值调用doPointConstraint()。
batchConnect()
完全不指定类型和参数的情况下,默认情况下必须使用这些默认值调用doParentConstraint()
python大神给出的解决方案
def myExample(**kwargs):
if kwargs.get("width") and kwargs.get("w"):
cmds.error("same flag used two times")
else:
myWidth = kwargs.get("width") or kwargs.get("w") or "nothing"
print(myWidth)
myExample(width=200)
我曾经在某些脚本中这样做
编辑-
如果需要多次,创建自定义类可能很容易:
class mimicKwargs:
def __init__(self, labelLong, labelShort, defautValue,kwargDic):
if kwargDic.get(labelLong) and kwargDic.get(labelShort):
cmds.error("same flag used two times")
else:
self.userInput = kwargDic.get(labelLong) or kwargDic.get(labelShort) or defautValue
def output(self):
return self.userInput
def myExample(**kwargs):
myWidth = mimicKwargs("width", "w", 150, kwargs).output()
print(myWidth)
myExample(width=200)#
myExample()#print 150