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

Explicit passing named (keyword) arguments when used with formal (positional), *args and **kwargs

我有以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/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)

以上代码输出:

1
2
3
4
5
6
7
8
9
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

正如您所看到的,默认参数是传递给"two"。但是我不想给默认变量赋任何东西,除非我明确地说出来。换句话说,我希望上面的命令返回这个:

1
2
3
4
5
6
7
8
9
10
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)

1
2
3
4
5
6
7
8
9
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"参数的kwargs,则可以使用pop方法将其从kwargs字典中删除(请参见此处)。以下代码的行为与您想要的一样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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)

它的工作原理和你想问的问题类似