Python中的**kwargs有什么用途?
我知道你可以在表上执行objects.filter并传递一个**kwargs参数。
我也可以这样做来指定时间增量,即时间增量(小时=时间1)吗?
它到底是如何工作的?是否归类为“开箱”?比如a,b=1,2?
Python中的**kwargs有什么用途?
我知道你可以在表上执行objects.filter并传递一个**kwargs参数。
我也可以这样做来指定时间增量,即时间增量(小时=时间1)吗?
它到底是如何工作的?是否归类为“开箱”?比如a,b=1,2?
当前回答
这是了解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只是一个添加到参数中的字典。
字典可以包含键、值对。这就是夸格夫妇。好的,就是这样。
做什么并不是那么简单。
例如(非常假设),您有一个接口,它只调用其他例程来完成任务:
def myDo(what, where, why):
if what == 'swim':
doSwim(where, why)
elif what == 'walk':
doWalk(where, why)
...
现在你得到了一个新的方法“驱动”:
elif what == 'drive':
doDrive(where, why, vehicle)
但是等一下,有一个新的参数“车辆”——你以前不知道。现在必须将其添加到myDo函数的签名中。
在这里,您可以将夸rgs放入游戏中——只需将夸rg斯添加到签名中即可:
def myDo(what, where, why, **kwargs):
if what == 'drive':
doDrive(where, why, **kwargs)
elif what == 'swim':
doSwim(where, why, **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是一种语法糖,可以将名称参数作为字典传递(对于func),或将字典作为命名参数传递(对于func)
在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.
只是另一种思考方式。