Python中的**kwargs有什么用途?

我知道你可以在表上执行objects.filter并传递一个**kwargs参数。 

我也可以这样做来指定时间增量,即时间增量(小时=时间1)吗?

它到底是如何工作的?是否归类为“开箱”?比如a,b=1,2?


当前回答

在Java中,使用构造函数重载类并允许多个输入参数。在python中,可以使用kwargs来提供类似的行为。

java示例:https://beginnersbook.com/2013/05/constructor-overloading/

python示例:

class Robot():
    # name is an arg and color is a kwarg
    def __init__(self,name, color='red'):
        self.name = name
        self.color = color

red_robot = Robot('Bob')
blue_robot = Robot('Bob', color='blue')

print("I am a {color} robot named {name}.".format(color=red_robot.color, name=red_robot.name))
print("I am a {color} robot named {name}.".format(color=blue_robot.color, name=blue_robot.name))

>>> I am a red robot named Bob.
>>> I am a blue robot named Bob.

只是另一种思考方式。

其他回答

此外,您还可以在调用kwargs函数时混合使用不同的用法:

def test(**kwargs):
    print kwargs['a']
    print kwargs['b']
    print kwargs['c']


args = { 'b': 2, 'c': 3}

test( a=1, **args )

给出以下输出:

1
2
3

注意,**kwargs必须是最后一个参数

这是了解python解包的简单示例,

>>> def f(*args, **kwargs):
...    print 'args', args, 'kwargs', kwargs

eg1:

>>>f(1, 2)
>>> args (1,2) kwargs {} #args return parameter without reference as a tuple
>>>f(a = 1, b = 2)
>>> args () kwargs {'a': 1, 'b': 2} #args is empty tuple and kwargs return parameter with reference as a dictionary

您可以使用**kwargs让函数接受任意数量的关键字参数(“kwargs”表示“关键字参数”):

>>> def print_keyword_args(**kwargs):
...     # kwargs is a dict of the keyword args passed to the function
...     for key, value in kwargs.iteritems():
...         print "%s = %s" % (key, value)
... 
>>> print_keyword_args(first_name="John", last_name="Doe")
first_name = John
last_name = Doe

通过构造关键字参数字典并将其传递给函数,也可以在调用函数时使用**kwargs语法:

>>> kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'}
>>> print_keyword_args(**kwargs)
first_name = Bobby
last_name = Smith

Python教程包含了它如何工作的很好的解释,以及一些很好的示例。

Python 3更新

对于Python 3,使用items()代替itertimes()

kwargs是一种语法糖,可以将名称参数作为字典传递(对于func),或将字典作为命名参数传递(对于func)

下面是一个我希望有帮助的例子:

#! /usr/bin/env python
#
def g( **kwargs) :
  print ( "In g ready to print kwargs" )
  print kwargs
  print ( "in g, calling f")
  f ( **kwargs )
  print ( "In g, after returning from f")

def f( **kwargs ) :
  print ( "in f, printing kwargs")
  print ( kwargs )
  print ( "In f, after printing kwargs")


g( a="red", b=5, c="Nassau")

g( q="purple", w="W", c="Charlie", d=[4, 3, 6] )

运行程序时,您将获得:

$ python kwargs_demo.py 
In g ready to print kwargs
{'a': 'red', 'c': 'Nassau', 'b': 5}
in g, calling f
in f, printing kwargs
{'a': 'red', 'c': 'Nassau', 'b': 5}
In f, after printing kwargs
In g, after returning from f
In g ready to print kwargs
{'q': 'purple', 'c': 'Charlie', 'd': [4, 3, 6], 'w': 'W'}
in g, calling f
in f, printing kwargs
{'q': 'purple', 'c': 'Charlie', 'd': [4, 3, 6], 'w': 'W'}
In f, after printing kwargs
In g, after returning from f

这里的关键是调用中命名参数的可变数量转换为函数中的字典。