开发者

Behavior of buggy parameter passing

I have a function:

def greeter(name, greeting, punc):
    print greeting+', '+name+pun开发者_JAVA百科c

I have a dictionary with parameters:

params={'name':'Mark','greeting':'How are you','punc':'?'}

When I call the function as greeter(**params), I get the expected output How are you, Mark?. But When I call like this greeter(*params), I get the output name, puncgreeting. Looks like a list of keys from params has been passed to greeter. What is actually happening here?

Just curious.


Looks like a list of keys from params has been passed to greeter. What is actually happening here?

That is indeed what is happening, more or less.

*x expects x to be an iterable, and iterates over it, interpreting the results as arguments one by one. Iterating over a dict, by default, iterates over its keys. (You could get name/value pairs instead, for example, with greeter(*(params.items())), but the dict would still be unsorted so order of iteration would be unreliable.)


Just as iterating over a dict yields keys, so does using it in positional expansion in this manner.

print list(params)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜