2014-03-26 54 views
3

我想測試使用字典來調用函數的概念,因爲python沒有case switch,我不想寫出一大堆if語句。然而,每當我試圖把功能的字典,我得到如下:函數字典的語法?

def hello(): 
... print 'hello world' 
... 
>>> fundict = {'hello':hello()} 
hello world 
>>> fundict 
{'hello': None} 
>>> fundict = {'hello':hello} 
>>> fundict['hello'] 
<function hello at 0x7fa539a87578> 

我怎麼叫fundict所以叫時運行hello()?我研究了一些其他的堆棧問題,但我沒有掌握語法,或者可能不理解它在給我一個地址。

+0

這兩個答案都很好,很具描述性。 – JFA

回答

1

在Python的所有對象都是一流(讀great article by Guido)。這基本上意味着你可以將它們分配給變量,比較它們,將它們作爲參數傳遞等。例如:

class C(object): 
    pass 

class_c = C 

# they are the same 
assert class_c is C 

# they are both instance of C 
instance1 = class_c() 
instance2 = C() 

def f(): 
    pass 

function_f = f 

# again, they are the same 
assert function_f is function 

# both results are results from function f 
result1 = f() 
result2 = function_f() 

這同樣也適用於實例方法(綁定和未綁定),靜態方法和類方法。因爲你可以把它們當作變量,你可以把它們放入一個字典:

fundict = {'hello' : hello} 

,並在以後使用它們:

function = fundict['hello'] 
function() 

# or less readable: 
fundict['hello']() 

您有怪異的輸出,你會與看到同樣的事情原始hello

>>> fundict['hello'] 
<function hello at 0x7fa539a87578> 
>>> hello 
<function hello at 0x7fa539a87578> 
7

您調用返回的對象:

fundict['hello']() 

您存儲功能正常對象;存儲的內容僅僅是一個參考,就像原始名稱hello是對該函數的引用。只需通過添加()(如果函數帶有參數)來調用參考。

演示:

>>> def hello(name='world'): 
...  print 'hello', name 
... 
>>> hello 
<function hello at 0x10980a320> 
>>> fundict = {'hello': hello} 
>>> fundict['hello'] 
<function hello at 0x10980a320> 
>>> fundict['hello']() 
hello world 
>>> fundict['hello']('JFA') 
hello JFA 
+0

@DSM這是他的第一次嘗試;第二次嘗試將其正確存儲。 – chepner

+0

@chepner:啊,好點。 – DSM