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())
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…