Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

python - ** wargs的目的和用途是什么?(What is the purpose and use of **kwargs?)

What are the uses for **kwargs in Python?

(**kwargs在Python中有什么用?)

I know you can do an objects.filter on a table and pass in a **kwargs argument.

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

Can I also do this for specifying time deltas ie timedelta(hours = time1) ?

(我也可以指定时间增量, timedelta(hours = time1)吗?)

How exactly does it work?

(它是如何工作的?)

Is it classes as 'unpacking'?

(它被归类为“拆包”吗?)

Like a,b=1,2 ?

(像a,b=1,2 ?)

  ask by Federer translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use **kwargs to let your functions take an arbitrary number of keyword arguments ("kwargs" means "keyword arguments"):

(您可以使用**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

You can also use the **kwargs syntax when calling functions by constructing a dictionary of keyword arguments and passing it to your function:

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

>>> 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教程很好地解释了它的工作方式,并提供了一些不错的示例。)

<--Update-->

(<-更新->)

For people using Python 3, instead of iteritems(), use items()

(对于使用Python 3的人,请使用items()代替iteritems())


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...