"**"在python中意味着什么?

DNB*_*ims 10 python python-3.x

可能重复:
**和*对python参数做了什么?
*args和**kwargs是什么意思?

简单程序:

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.")     
Run Code Online (Sandbox Code Playgroud)

专注于这一行:

    story = storyFormat.format(**userPicks)
Run Code Online (Sandbox Code Playgroud)

什么**意思?为什么不通过平原userPicks

Man*_*y D 26

'**'接受一个字典并提取其内容并将它们作为参数传递给函数.以此功能为例:

def func(a=1, b=2, c=3):
   print a
   print b
   print b
Run Code Online (Sandbox Code Playgroud)

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

func(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

但是您也可以使用这样存储的参数填充字典:

params = {'a': 2, 'b': 3, 'c': 4}
Run Code Online (Sandbox Code Playgroud)

现在你可以将它传递给函数:

func(**params)
Run Code Online (Sandbox Code Playgroud)

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

def func(*args, **kwargs):
   ...
Run Code Online (Sandbox Code Playgroud)

*args提取位置参数并**kwargs提取关键字参数.

  • 请注意,“params”字典的键值必须与“func”定义中列出的可选参数的名称匹配,否则将出现“TypeError”。 (2认同)

mar*_*xus 5

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