“**”在python中是啥意思? [复制]

Posted

技术标签:

【中文标题】“**”在python中是啥意思? [复制]【英文标题】:What does "**" mean in python? [duplicate]“**”在python中是什么意思? [复制] 【发布时间】:2011-12-23 02:43:07 【问题描述】:

可能重复:What does ** and * do for python parameters?What does *args and **kwargs mean?

简单程序:

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

【问题讨论】:

【参考方案1】:

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

【讨论】:

【参考方案2】:

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

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 提取关键字参数。

【讨论】:

那么,它可以用字典键映射回参数,对吗?这个功能/特性叫什么?我发现它非常有趣且功能强大,这仅适用于 python 吗? @DNB5brims,我相信这被称为“解构”。它正在进入其他语言,例如 javascript (ECMAScript 2015)。 注意paramsdict的键值必须与func定义中列出的可选参数的名称匹配,否则会出现TypeError

以上是关于“**”在python中是啥意思? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

以下代码中的 zip(*res) 在 python 中是啥意思? [复制]

__init__(self) 在 Python 中是啥意思? [复制]

这个符号在 C++ 中是啥意思? [复制]

这个f在这句话中是啥意思? [复制]

“?”是啥意思?在 Erlang 中是啥意思? [复制]

“||”是啥意思在 var 语句中是啥意思? [复制]