2

所以我有一个这样定义的函数:

def getDistnace(self, strings, parentD, nodeName, nodeDistance):

我用它来称呼它:

Node.getDistnace(newNode, strings, parentD, nodeName=None, nodeDistance=None)

Node.getDistnace(node, strings=None, parentD=None, nodeName, nodeDistance)

它们都来自其他两个不同的功能。但我的问题是我收到一条错误消息,指出存在non-keyword arg after keyword arg.

有没有办法解决这个错误?第一个Node.getDistnace添加stringsandparentDgetDistance,第二个Node.getDistnace添加nodeNameandnodeDistance到函数。

4

1 回答 1

7

你所有的参数都是位置的,你根本不需要使用关键字:

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)

这里我移到nodeDistance了关键字参数的前面,但是 Python 仍然会将它匹配到getDistnace方法的最后一个参数。

于 2012-07-12T18:04:00.273 回答