What does "**" mean in python?
Possible Duplicate:
What does ** and * do for python parameters?
What does *args and **kwargs mean?
Simple program:
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.")
Focus on this line:
story = storyFormat.format(**userPicks)
What does the **
mean? Why not just pass a plain userPicks
?
'**' takes a dict and extracts its contents and passes them as parameters to a function. Take this function for example:
def func(a=1, b=2, c=3):
print a
print b
print b
Now normally you could call this function like this:
func(1, 2, 3)
But you can also populate a dictionary with those parameters stored like so:
params = {'a': 2, 'b': 3, 'c': 4}
Now you can pass this to the function:
func(**params)
Sometimes you'll see this format in function definitions:
def func(*args, **kwargs):
...
*args
extracts positional parameters and **kwargs
extract keyword parameters.
**means kwargs. here is a good article about it.
read this: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
你可以阅读Python教程的这一部分和这篇文章。
链接地址: http://www.djcxy.com/p/9056.html上一篇: python中的kwargs保留字。 这是什么意思?
下一篇: “**”在Python中意味着什么?