2014-03-05 133 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]()