2011-11-06 60 views
4

可能重复:
What does ** and * do for python parameters?
What does *args and **kwargs mean?“**”在Python中意味着什么?

简单的程序:

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

回答

13

'**'需要一个字典并提取其内容并将它们作为参数传递给函数。就拿这个功能,例如:

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

+0

所以,它可以把字典键映射回参数,是吗?这个功能叫做什么功能?我发现它非常有趣和强大,这是唯一的蟒蛇吗? – DNB5brims

+0

@ DNB5brims,我相信这被称为“解构”。它正在寻找其他语言,如Javascript(ECMAScript 2015)。 – johnsimer

+0

请注意,'params'字典的键值必须与'func'定义中列出的可选参数的名称相匹配,否则会出现'TypeError'。 –