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

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

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

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


当前回答

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

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

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

其他回答

正在解压缩词典

**拆开词典。

This

func(a=1, b=2, c=3)

args = {'a': 1, 'b': 2, 'c':3}
func(**args)

如果您必须构造参数,这很有用:

args = {'name': person.name}
if hasattr(person, "address"):
    args["address"] = person.address
func(**args)  # either expanded to func(name=person.name) or
              #                    func(name=person.name, address=person.address)

函数的包装参数

对python 3使用.items()而不是.iteritems()

def setstyle(**styles):
    for key, value in styles.iteritems():      # styles is a regular dictionary
        setattr(someobject, key, value)

这使您可以像这样使用函数:

setstyle(color="red", bold=False)

笔记

kwargs是用于关键字参数的变量名,可以使用另一个变量名。重要的一点是它是一本字典,并且用双星号运算符**进行了解包。其他可迭代项使用单个星号运算符解包*为了避免混淆,最好分别使用字典和其他可迭代变量的可识别变量名kwargs和args。


资源

PEP 448:其他解包概括真实Python:Python args和kwargs:解密在函数签名中,变量名前的*和**意味着什么?

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

这是了解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

在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.

只是另一种思考方式。

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

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

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