**kwargs 的目的和用途是什么? [英] What is the purpose and use of **kwargs?
问题描述
**kwargs
在 Python 中有什么用途?
我知道您可以在表上执行 objects.filter
并传入 **kwargs
参数.
我也可以这样做来指定时间增量,即 timedelta(hours = time1)
?
它究竟是如何工作的?它是拆包"类吗?像a,b=1,2
?
您可以使用 **kwargs
让您的函数接受任意数量的关键字参数(kwargs"的意思是关键字参数"):
您还可以在调用函数时使用 **kwargs
语法,方法是构建关键字参数字典并将其传递给您的函数:
Python 教程 很好地解释了它的工作原理,以及一些不错的例子.
Python 3 更新
对于 Python 3,使用 iteritems()"noreferrer">items()
What are the uses for **kwargs
in Python?
I know you can do an objects.filter
on a table and pass in a **kwargs
argument.
Can I also do this for specifying time deltas i.e. timedelta(hours = time1)
?
How exactly does it work? Is it classes as 'unpacking'? Like a,b=1,2
?
You can use **kwargs
to let your functions take an arbitrary number of keyword arguments ("kwargs" means "keyword arguments"):
>>> 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
You can also use the **kwargs
syntax when calling functions by constructing a dictionary of keyword arguments and passing it to your function:
>>> kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'}
>>> print_keyword_args(**kwargs)
first_name = Bobby
last_name = Smith
The Python Tutorial contains a good explanation of how it works, along with some nice examples.
Python 3 update
For Python 3, instead of iteritems()
, use items()
这篇关于**kwargs 的目的和用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!