在 Python 中使用具有可变长度未命名参数的命名参数

发布于 2024-09-08 02:34:43 字数 453 浏览 11 评论 0原文

如果这个问题已经被问/回答了,我深表歉意,我本以为会出现这种情况,但无法找到任何相关的问题...

我想创建一个 python 函数,它接受两个强制参数,一个命名参数,以及一些未知数量的其他非命名参数:

def my_function(arg1, arg2, arg3=None, *other_args):
    pass

这在 Python 2.x 中可能吗?
除了可变长度参数列表之外,函数还可以接受命名参数吗?

我相信答案是“否”,在这种情况下,我认为唯一可用的解决方案类似于以下内容:

def my_function(arg1, arg2, **kwargs):
    arg3 = kwargs["arg3"]
    other_args = kwargs["other_args"]

这是正确的吗?

I apologize if this question has already been asked/answered, I would have expected that to be the case but was unable to find any related questions...

I'd like to create a python function that takes two mandatory arguments, one named argument, and some unknown number of other, non-named arguments as so:

def my_function(arg1, arg2, arg3=None, *other_args):
    pass

Is this possible in Python 2.x?
Can a function accept named arguments in addition to a variable length argument list?

I believe the answer is 'no', in which case I'm thinking the only solution available to me would be something similar to the following:

def my_function(arg1, arg2, **kwargs):
    arg3 = kwargs["arg3"]
    other_args = kwargs["other_args"]

Is that correct?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无人问我粥可暖 2024-09-15 02:34:43

该语法当然是有效的,但我认为您的意思是您可以编写函数签名,使得 arg3 仅在用作命名参数时才绑定(例如 my_function(1, 2, arg3 = 3)),否则让前两个参数之后的所有参数都被 *other_args 捕获,在这种情况下答案是否定的。可选参数可以通过命名来指定,但它们也像普通参数一样具有位置性,并且如果有足够的参数可用,则在使用 *args**kwargs 等包罗万象的参数之前填充它们

我可能会像你一样使用关键字参数来编写它

That syntax is certainly valid, but I think you mean can you write the function signature such that arg3 is only bound if it's used as a named parameter (e.g. my_function(1, 2, arg3 = 3)), and otherwise to have all arguments past the first two be caught by *other_args, in which case the answer is no. Optional arguments can be specified by naming, but they're also positional like normal arguments and are filled in if enough parameters are available, before resorting to catch-alls like *args or **kwargs.

I would probably write it exactly as you did, using keyword arguments

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文