2012-07-12 69 views
2

所以我定义为这样的功能:如何在方法调用中使用关键字arg之后的非关键字arg?

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) 

这两者都是从2种不同功能。但我的问题是,我得到一个错误,说明有一个non-keyword arg after keyword arg

有没有办法解决这个错误?第一个Node.getDistnace增加了stringsparentDgetDistance,第二个Node.getDistnace增加了nodeNamenodeDistance的功能。

回答

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方法的最后一个参数。

相关问题