Sea*_*ean 2 python arguments function keyword
所以我有一个定义如下的函数:
def getDistnace(self, strings, parentD, nodeName, nodeDistance):
Run Code Online (Sandbox Code Playgroud)
我称之为:
Node.getDistnace(newNode, strings, parentD, nodeName=None, nodeDistance=None)
Run Code Online (Sandbox Code Playgroud)
和
Node.getDistnace(node, strings=None, parentD=None, nodeName, nodeDistance)
Run Code Online (Sandbox Code Playgroud)
这两个来自其他两个不同的功能.但我的问题是我得到一个错误,说明有一个non-keyword arg after keyword arg.
有没有办法解决这个错误?第一个Node.getDistnace加strings和parentD来getDistance,第二个Node.getDistnace加nodeName和nodeDistance的功能.
您的所有参数都是位置参数,您根本不需要使用关键字:
Node.getDistnace(newNode, strings, parentD, None, None)
Node.getDistnace(node, None, None, nodeName, nodeDistance)
Run Code Online (Sandbox Code Playgroud)
我认为你混淆局部变量(你传递给函数的东西)和函数的参数名称.它们碰巧在您的代码中匹配,但并不要求它们匹配.
以下代码与第一个示例具有相同的效果:
arg1, arg2, arg3 = newNode, strings, parentD
Node.getDistnace(arg1, arg2, arg3, None, None)
Run Code Online (Sandbox Code Playgroud)
如果你确实想使用关键字参数,那很好,但是它们不能跟随位置参数.然后你可以改变顺序,python仍会匹配它们:
Node.getDistnace(node, nodeDistance=nodeDistance, strings=None, parentD=None, nodeName=nodeName)
Run Code Online (Sandbox Code Playgroud)
在这里,我移到nodeDistance了关键字参数的前面,但Python仍然会将它与方法的最后一个参数匹配getDistnace.
| 归档时间: |
|
| 查看次数: |
6084 次 |
| 最近记录: |