2014-03-05 135 views
3

我试图使在python其中,如果用户选择了一些在执行不同的功能选项的菜单:访问蟒蛇字典值

def options(x): 
    return { 
     1: f1(), 
     2: f2() 
    }[x] 

def f1(): 
    print "hi" 

def f2(): 
    print "bye" 

然而,好,我叫

options(1) 

我得到:

hi 
bye 

,并同当我打电话options(2)

这是怎么回事?

回答

7

要调用的函数,而不是assiging他们对键

def f1(): 
    print "hi" 

def f2(): 
    print "bye" 

functions = {1: f1, 2: f2} # dict of functions (Note: no parenthesis) 

def options(x): 
    return functions[x]() # Get the function against the index and invoke it 

options(1) 
# hi 

options(2) 
# bye 
1

你的字典是建立与返回值的功能;不要调用函数,直到从字典采摘之后:

def options(x): 
    return { 
     1: f1, 
     2: f2 
    }[x]() 

现在您存储只是一个在字典中的职能参考,并调用所选择的功能后取回。

演示:

>>> def f1(): 
...  print "hi" 
... 
>>> def f2(): 
...  print "bye" 
... 
>>> def options(x): 
...  return { 
...   1: f1, 
...   2: f2 
...  }[x]() 
... 
>>> options(1) 
hi 
>>> options(2) 
bye 
0

与回报更换打印并用,那么它会工作返回。或者使用fortheye版本。

0

问题在于,在构建字典时调用函数(使用())。离开后,只有在从字典中获得价值后才应用它们:

def options(x): 
    return { 
     1: f1, 
     2: f2 
    }[x]()