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



我有以下代码:

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

这可能吗?

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

正如Sam所指出的,你可以通过从夸尔格身上获取价值来实现同样的行为。如果您的逻辑依赖于包含"默认"参数的kwargs而不是,则可以使用pop方法将其从kwargs字典中删除(请参阅此处(。以下代码的行为与您想要的一样:

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)

它的工作原理类似于您在问题中想要的方式

最新更新