**(双星/星号)和 *(星/星号)对参数有什么作用? [英] What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
问题描述
在下面的方法定义中,*
和 **
对 param2
有什么作用?
In the following method definitions, what does the *
and **
do for param2
?
def foo(param1, *param2):
def bar(param1, **param2):
推荐答案
*args
和 **kwargs
是一个常见的习惯用法,它允许函数有任意数量的参数如更多关于定义函数部分所述在 Python 文档中.
The *args
and **kwargs
is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation.
*args
将为您提供所有函数参数 作为元组:
The *args
will give you all function parameters as a tuple:
def foo(*args):
for a in args:
print(a)
foo(1)
# 1
foo(1,2,3)
# 1
# 2
# 3
**kwargs
会给你所有关键字参数,除了那些对应于作为字典的形式参数的参数.
The **kwargs
will give you all
keyword arguments except for those corresponding to a formal parameter as a dictionary.
def bar(**kwargs):
for a in kwargs:
print(a, kwargs[a])
bar(name='one', age=27)
# name one
# age 27
这两种习语都可以与普通参数混合使用,以允许一组固定参数和一些可变参数:
Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:
def foo(kind, *args, **kwargs):
pass
也可以反过来使用:
def foo(a, b, c):
print(a, b, c)
obj = {'b':10, 'c':'lee'}
foo(100,**obj)
# 100 10 lee
*l
习语的另一种用法是在调用函数时解压参数列表.
Another usage of the *l
idiom is to unpack argument lists when calling a function.
def foo(bar, lee):
print(bar, lee)
l = [1,2]
foo(*l)
# 1 2
在 Python 3 中,可以在赋值的左侧使用 *l
(Extended Iterable Unpacking),尽管在这种情况下它给出了一个列表而不是一个元组:
In Python 3 it is possible to use *l
on the left side of an assignment (Extended Iterable Unpacking), though it gives a list instead of a tuple in this context:
first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]
Python 3 还添加了新语义(请参阅 PEP 3102):
Also Python 3 adds new semantic (refer PEP 3102):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass
此类函数只接受3个位置参数,*
之后的所有内容只能作为关键字参数传递.
Such function accepts only 3 positional arguments, and everything after *
can only be passed as keyword arguments.
- 一个 Python
dict
,语义上用于关键字参数传递,是任意排序的.但是,在 Python 3.6 中,关键字参数保证记住插入顺序. **kwargs
中元素的顺序现在对应于关键字参数传递给函数的顺序."- Python 3.6 的新增功能- 事实上,CPython 3.6 中的所有 dict 都会记住插入顺序作为实现细节,这在 Python 3.7 中成为标准.
- A Python
dict
, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order. - "The order of elements in
**kwargs
now corresponds to the order in which keyword arguments were passed to the function." - What’s New In Python 3.6 - In fact, all dicts in CPython 3.6 will remember insertion order as an implementation detail, this becomes standard in Python 3.7.
这篇关于**(双星/星号)和 *(星/星号)对参数有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!