【问题标题】:Explicit passing named (keyword) arguments when used with formal (positional), *args and **kwargs与正式(位置)、*args 和 **kwargs 一起使用时显式传递命名(关键字)参数
【发布时间】:2015-09-20 23:19:46
【问题描述】:

我有以下代码:

#!/usr/bin/python

import sys
import os

from pprint import pprint as pp

def test_var_args(farg, default=1, *args, **kwargs):
    print "type of args is", type(args)
    print "type of args is", type(kwargs)

    print "formal arg:", farg
    print "default arg:", default

    for arg in args:
        print "another arg:", arg

    for key in kwargs:
        print "another keyword arg: %s: %s" % (key, kwargs[key])

    print "last argument from args:", args[-1]


test_var_args(1, "two", 3, 4, myarg2="two", myarg3=3)

以上代码输出:

type of args is <type 'tuple'>
type of args is <type 'dict'>
formal arg: 1
default arg: two
another arg: 3
another arg: 4
another keyword arg: myarg2: two
another keyword arg: myarg3: 3
last argument from args: 4

如您所见,默认参数是“两个”。但是我不想给默认变量分配任何东西,除非我明确地说出来。换句话说,我希望上述命令返回:

type of args is <type 'tuple'>
type of args is <type 'dict'>
formal arg: 1
default arg: 1
another arg: two
another arg: 3
another arg: 4
another keyword arg: myarg2: two
another keyword arg: myarg3: 3
last argument from args: 4

应明确更改默认变量,例如使用这样的东西(以下命令给出编译错误,这只是我的尝试) test_var_args(1, default="two", 3, 4, myarg2="two", myarg3=3):

type of args is <type 'tuple'>
type of args is <type 'dict'>
formal arg: 1
default arg: two
another arg: 3
another arg: 4
another keyword arg: myarg2: two
another keyword arg: myarg3: 3
last argument from args: 4

我尝试过以下操作,但它也返回编译错误: test_var_args(1,, 3, 4, myarg2="two", myarg3=3)

这可能吗?

【问题讨论】:

  • default 视为可选kwarg 并在您的方法中包含default = kwargs.get('default', 1) 行有什么问题?
  • 可能没什么,请您在回答中发布工作代码 sn-p。我尝试根据您的建议修改我的代码,并将此 default = kwargs.get('default', 1) 添加为我在子例程中的第一行,但它返回我编译错误和/或在以下方式调用时将 3 作为默认值 test_var_args(1, 3, 4, myarg2="two", myarg3=3, default="default")
  • @WakanTanka 看看我的答案,它包含一个示例:D
  • 谢谢你们,这有帮助

标签: python arguments


【解决方案1】:

很遗憾,我认为这是不可能的。

正如 Sam 所指出的,您可以通过从 kwargs 中取出价值来实现相同的行为。如果您的逻辑依赖依赖于包含“默认”参数的 kwargs ,则可以使用 pop 方法将其从 kwargs 字典中删除(请参阅 here)。以下代码的行为如您所愿:

import sys
import os

from pprint import pprint as pp

def test_var_args(farg, *args, **kwargs):
    print "type of args is", type(args)
    print "type of args is", type(kwargs)

    print "formal arg:", farg
    print 'default', kwargs.pop('default', 1)

    for arg in args:
        print "another arg:", arg

    for key in kwargs:
        print "another keyword arg: %s: %s" % (key, kwargs[key])

    print "last argument from args:", args[-1]

# Sample call
test_var_args(1, 3, 4, default="two", myarg2="two", myarg3=3)

这与您在问题中想要的方式相似

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2020-11-03
    • 2020-10-18
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    相关资源
    最近更新 更多