在Python中“**”是什么意思?

24 投票
2 回答
60945 浏览
提问于 2025-04-17 05:45

简单的程序:

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 呢?

2 个回答

5

**代表的是关键字参数(kwargs)。这里有一篇不错的文章可以了解更多内容。
你可以阅读这个链接: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

55

这个'**'符号是用来处理字典的,它可以把字典里的内容提取出来,然后作为参数传递给一个函数。举个例子,看看这个函数:

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

通常,你可以这样调用这个函数:

func(1, 2, 3)

但是你也可以先把这些参数放到一个字典里,像这样:

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

然后你就可以把这个字典传给函数了:

func(**params)

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

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

*args 是用来提取位置参数的,而 **kwargs 是用来提取关键字参数的。

撰写回答