Python 方法/函数参数以星号和对偶星号开头

我不能理解这些类型的函数在哪里使用,以及这些参数与普通参数的工作方式有什么不同。我遇到他们很多次,但从来没有机会了解他们正确的。

例如:

def method(self, *links, **locks):
#some foo
#some bar
return

我知道我可以搜索文件,但我不知道要搜索什么。

36253 次浏览

The *args and **keywordargs forms are used for passing lists of arguments and dictionaries of arguments, respectively. So if I had a function like this:

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)

*args behaves like a list, and **keywordargs behaves like a dictionary, but you don't have to explicitly pass a list or a dict to the function.

See this for more examples.