Python 如何在方法调用中的关键字arg之后使用非关键字arg?
所以我有一个这样定义的函数:Python 如何在方法调用中的关键字arg之后使用非关键字arg?,python,function,arguments,keyword,Python,Function,Arguments,Keyword,所以我有一个这样定义的函数: def getDistnace(self, strings, parentD, nodeName, nodeDistance): 我称之为: Node.getDistnace(newNode, strings, parentD, nodeName=None, nodeDistance=None) 及 这两个函数都来自另外两个不同的函数。但我的问题是,我得到一个错误,说明在关键字arg之后有一个非关键字arg 有没有办法避免这个错误?第一个节点.getDistna
def getDistnace(self, strings, parentD, nodeName, nodeDistance):
我称之为:
Node.getDistnace(newNode, strings, parentD, nodeName=None, nodeDistance=None)
及
这两个函数都来自另外两个不同的函数。但我的问题是,我得到一个错误,说明在关键字arg之后有一个非关键字arg
有没有办法避免这个错误?第一个节点.getDistnace
将字符串
和父对象
添加到getDistance
,第二个节点.getDistnace
将节点名
和节点名
添加到函数中。所有参数都是定位的,根本不需要使用关键字:
Node.getDistnace(newNode, strings, parentD, None, None)
Node.getDistnace(node, None, None, nodeName, nodeDistance)
我认为您混淆了局部变量(传入函数的内容)和函数的参数名称。它们在代码中恰好匹配,但并不要求它们匹配
以下代码的效果与第一个示例相同:
arg1, arg2, arg3 = newNode, strings, parentD
Node.getDistnace(arg1, arg2, arg3, None, None)
如果您确实想使用关键字参数,这很好,但它们后面不能跟位置参数。然后,您可以更改顺序,python仍将匹配它们:
Node.getDistnace(node, nodeDistance=nodeDistance, strings=None, parentD=None, nodeName=nodeName)
在这里,我将nodeInstance
移到了关键字参数的前面,但是Python仍然会将它与getDistnace
方法的最后一个参数相匹配
Node.getDistnace(node, nodeDistance=nodeDistance, strings=None, parentD=None, nodeName=nodeName)