在python中”**”是什么意思?

What does “**” mean in python?

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
What does ** and * do for python parameters?
What does *args and **kwargs mean?

简单程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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.")

关注这一行:

1
    story = storyFormat.format(**userPicks)

**是什么意思?为什么不直接通过一个普通的userPicks


"**"接受dict并提取其内容,并将其作为参数传递给函数。以这个函数为例:

1
2
3
4
def func(a=1, b=2, c=3):
   print a
   print b
   print b

现在通常可以这样调用这个函数:

1
func(1, 2, 3)

但您也可以使用存储的参数来填充字典,如下所示:

1
params = {'a': 2, 'b': 3, 'c': 4}

现在可以将此传递给函数:

1
func(**params)

有时您会在函数定义中看到这种格式:

1
2
def func(*args, **kwargs):
   ...

*args提取位置参数,**kwargs提取关键字参数。


**表示Kwargs。这是一篇关于它的好文章。
请阅读:http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/


您可以阅读Python教程的这一部分和本文。