以星号和双星号开头的 Python 方法/函数参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4306574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python method/function arguments starting with asterisk and dual asterisk
提问by Shiv Deepak
I am not able understand where does these type of functions are used and how differently these arguments work from the normal arguments. I have encountered them many time but never got chance to understand them properly.
我无法理解这些类型的函数在哪里使用以及这些参数与普通参数的工作方式有何不同。我曾多次遇到它们,但从未有机会正确理解它们。
Ex:
前任:
def method(self, *links, **locks):
#some foo
#some bar
return
I know i could have search the documentation but i have no idea what to search for.
我知道我可以搜索文档,但我不知道要搜索什么。
采纳答案by Rafe Kettler
The *argsand **keywordargsforms are used for passing lists of arguments and dictionaries of arguments, respectively. So if I had a function like this:
的*args和**keywordargs的形式被分别用于传递的自变量的自变量列表和字典。所以如果我有这样的功能:
def printlist(*args):
for x in args:
print(x)
I could call it like this:
我可以这样称呼它:
printlist(1, 2, 3, 4, 5) # or as many more arguments as I'd like
For this
为了这
def printdict(**kwargs):
print(repr(kwargs))
printdict(john=10, jill=12, david=15)
*argsbehaves like a list, and **keywordargsbehaves like a dictionary, but you don't have to explicitly pass a listor a dictto the function.
*args行为类似于列表,**keywordargs行为类似于字典,但您不必显式地将 alist或 a传递dict给函数。
See thisfor more examples.
见这为更多的例子。

