【问题标题】:How to use a non-keyword arg after a keyword arg in a method call?如何在方法调用中的关键字 arg 之后使用非关键字 arg?
【发布时间】:2012-07-12 13:24:03
【问题描述】:

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

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.getDistnacestringsparentD 添加到getDistance,第二个Node.getDistnacenodeNamenodeDistance 添加到函数中。

【问题讨论】:

    标签: python function arguments keyword


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多