所以我很难理解*args和**kwargs的概念。
到目前为止,我了解到:
*args=参数列表-作为位置参数**kwargs=dictionary-其键成为单独的关键字参数,值成为这些参数的值。
我不知道这对什么编程任务有帮助。
也许 吧:
我想输入列表和字典作为函数的参数,同时作为通配符,这样我就可以传递任何参数了?
有没有一个简单的例子来解释如何使用*args和**kwargs?
另外,我发现的教程只使用了“*”和变量名。
*args和**kwargs只是占位符吗?还是在代码中使用的是*args或**kwarg?
下面是一个使用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}
使用*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类。
*args和**kwargs是Python的特殊魔力特性。想象一个可能有未知数量参数的函数。例如,无论出于何种原因,您都希望使用一个对未知数量的数字求和的函数(并且不希望使用内置的求和函数)。所以你写这个函数:
def sumFunction(*args):
result = 0
for x in args:
result += x
return result
并使用它:sumFunction(3,4,6,3,6,8,9)。
**kwargs有一个不同的功能。使用**kwargs,您可以为函数提供任意关键字参数,并且可以将它们作为字典进行访问。
def someFunction(**kwargs):
if 'text' in kwargs:
print kwargs['text']
调用someFunction(text=“foo”)将打印foo。
在编写包装函数(如装饰器)时,*args和**kwargs是有用的一种情况,这些包装函数需要能够接受任意参数以传递给被包装的函数。例如,一个简单的装饰器,它打印被包装函数的参数和返回值:
def mydecorator( f ):
@functools.wraps( f )
def wrapper( *args, **kwargs ):
print "Calling f", args, kwargs
v = f( *args, **kwargs )
print "f returned", v
return v
return wrapper
下面是一个使用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}