可能重复:
What does ** and * do for python parameters?
What does *args and **kwargs mean?“**”在Python中意味着什么?
简单的程序:
storyFormat = """
Once upon a time, deep in an ancient jungle,
there lived a {animal}. This {animal}
liked to eat {food}, but the jungle had
very little {food} to offer. One day, an
explorer found the {animal} and discovered
it liked {food}. The explorer took the
{animal} back to {city}, where it could
eat as much {food} as it wanted. However,
the {animal} became homesick, so the
explorer brought it back to the jungle,
leaving a large supply of {food}.
The End
"""
def tellStory():
userPicks = dict()
addPick('animal', userPicks)
addPick('food', userPicks)
addPick('city', userPicks)
story = storyFormat.format(**userPicks)
print(story)
def addPick(cue, dictionary):
'''Prompt for a user response using the cue string,
and place the cue-response pair in the dictionary.
'''
prompt = 'Enter an example for ' + cue + ': '
response = input(prompt).strip() # 3.2 Windows bug fix
dictionary[cue] = response
tellStory()
input("Press Enter to end the program.")
关注这一行:
story = storyFormat.format(**userPicks)
**
是什么意思?为什么不通过简单的userPicks
?
所以,它可以把字典键映射回参数,是吗?这个功能叫做什么功能?我发现它非常有趣和强大,这是唯一的蟒蛇吗? – DNB5brims
@ DNB5brims,我相信这被称为“解构”。它正在寻找其他语言,如Javascript(ECMAScript 2015)。 – johnsimer
请注意,'params'字典的键值必须与'func'定义中列出的可选参数的名称相匹配,否则会出现'TypeError'。 –