开发者

Python method/function arguments starting with asterisk and dual asterisk [duplicate]

开发者 https://www.devze.com 2023-01-27 06:13 出处:网络
This question already has answers here: What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
This question already has answers here: What does ** (double star/asterisk) and * (star/asterisk) do for parameters? (25 answers) Closed 4 years ago.

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消