当与正式(位置),* args和** kwargs一起使用时,显式传递命名(关键字)参数

时间:2015-07-03 07:43:48

标签: python arguments

我有以下代码:

#!/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

正如你所看到的,默认参数被传递了#34;两个&#34;。但我不想将默认变量分配给任何东西,除非我明确说出来。换句话说,我希望前面提到的命令返回:

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)

这可能吗?

1 个答案:

答案 0 :(得分:0)

不幸的是,我认为不可能。

Sam指出,你可以通过从kwargs中取出值来实现相同的行为。如果您的逻辑依赖 的kwargs上,其中包含&#34;默认&#34;参数,您可以使用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)

与您在问题中的表达方式类似