使用*args和**kwargs

2024-04-16 13:58:44 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我很难理解*args**kwargs的概念。

到目前为止,我了解到:

  • *args=参数列表-作为位置参数
  • **kwargs=dictionary-其键成为单独的关键字参数,值成为这些参数的值。

我不明白这对编程任务有什么帮助。

也许:

我想输入列表和字典作为函数的参数,同时作为通配符,这样我就可以传递任何参数了?

有没有一个简单的例子来解释如何使用*args**kwargs

另外,我找到的教程只使用了“*”和变量名。

*args**kwargs只是占位符还是在代码中正好使用*args**kwargs


Tags: 函数代码概念列表参数dictionary字典编程
3条回答

使用*args**kwargs非常有用的地方之一是子类化。

class Foo(object):
    def __init__(self, value1, value2):
        # do something with the values
        print value1, value2

class MyFoo(Foo):
    def __init__(self, *args, **kwargs):
        # do something else, don't care about the args
        print 'myfoo'
        super(MyFoo, self).__init__(*args, **kwargs)

这样就可以扩展Foo类的行为,而不必对Foo了解太多。如果您正在编程到一个可能会改变的API,这会非常方便。MyFoo只是将所有参数传递给Foo类。

The syntax is the ^{} and ^{}。名字*args**kwargs只是按惯例使用,但没有硬性要求。

当您不确定可以向函数传递多少个参数时,您可以使用*args,也就是说,它允许您向函数传递任意数量的参数。例如:

>>> def print_everything(*args):
        for count, thing in enumerate(args):
...         print( '{0}. {1}'.format(count, thing))
...
>>> print_everything('apple', 'banana', 'cabbage')
0. apple
1. banana
2. cabbage

类似地,**kwargs允许您处理未预先定义的命名参数:

>>> def table_things(**kwargs):
...     for name, value in kwargs.items():
...         print( '{0} = {1}'.format(name, value))
...
>>> table_things(apple = 'fruit', cabbage = 'vegetable')
cabbage = vegetable
apple = fruit

您也可以将这些参数与命名参数一起使用。显式参数首先获取值,然后将所有其他参数传递给*args**kwargs。命名参数排在列表的第一位。例如:

def table_things(titlestring, **kwargs)

您也可以在同一个函数定义中同时使用这两个函数,但是*args必须在**kwargs之前发生。

调用函数时还可以使用***语法。例如:

>>> def print_three_things(a, b, c):
...     print( 'a = {0}, b = {1}, c = {2}'.format(a,b,c))
...
>>> mylist = ['aardvark', 'baboon', 'cat']
>>> print_three_things(*mylist)
a = aardvark, b = baboon, c = cat

正如您在本例中看到的,它获取项目列表(或元组)并将其解包。通过这个,它将它们与函数中的参数相匹配。当然,在函数定义和函数调用中都可以有一个*

下面是一个使用3种不同类型参数的示例。

def func(required_arg, *args, **kwargs):
    # required_arg is a positional-only parameter.
    print required_arg

    # args is a tuple of positional arguments,
    # because the parameter name has * prepended.
    if args: # If args is not empty.
        print args

    # kwargs is a dictionary of keyword arguments,
    # because the parameter name has ** prepended.
    if kwargs: # If kwargs is not empty.
        print kwargs

>>> func()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func() takes at least 1 argument (0 given)

>>> func("required argument")
required argument

>>> func("required argument", 1, 2, '3')
required argument
(1, 2, '3')

>>> func("required argument", 1, 2, '3', keyword1=4, keyword2="foo")
required argument
(1, 2, '3')
{'keyword2': 'foo', 'keyword1': 4}

相关问题 更多 >