cuốn sách gpt4 ai đã làm

python - 如何在方法调用中的关键字 arg 之后使用非关键字 arg?

In lại Tác giả: Walker 123 更新时间:2023-11-28 20:50:53 27 4
mua khóa gpt4 Nike

所以我定义了一个函数:

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)

它们都来自另外两个不同的函数。但我的问题是我收到一条错误消息,指出在关键字 arg 之后有一个非关键字 arg.

有什么办法可以解决这个错误吗?第一个 Node.getDistnace Sẽ dâyparentD thêm vào getDistance 中,第二个 Node.getDistnace Sẽ nodeNamenodeDistance 添加到函数中。

câu trả lời hay nhất

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

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)

Nếu bạnThực ra想使用关键字参数,那很好,但它们后面不能跟位置参数。然后你可以改变顺序,python 仍然会匹配它们:

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

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

关于python - 如何在方法调用中的关键字 arg 之后使用非关键字 arg?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11457850/

27 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress