2016-05-17 93 views
0

如何使用變量作爲函數名稱,以便我可以獲取函數列表並在循環中初始化它們。我得到了我期望的錯誤,這是str對象不可調用的錯誤。但我不知道如何解決它。謝謝。如何在python中使用變量作爲函數名稱

#Open protocol configuration file 
config = configparser.ConfigParser() 
config.read("protocol.config") 

# Create new threads for each protocol that is configured 
protocols = ["ISO", "CMT", "ASCII"] 
threads = [] 
threadID = 0 

for protocol in protocols: 
     if (config.getboolean(protocol, "configured") == True): 
       threadID = threadID + 1 
       function_name = config.get(protocol, "protocol_func") 
       threads.append(function_name(threadID, config.get(protocol, "port"))) 

# Start new threads 
for thread in threads: 
     thread.start() 

print ("Exiting Main Protocol Manager Thread") 
+0

** **這些功能在哪裏?在特定的模塊?當前模塊?通常,將函數作爲字典鍵並進行查找是最乾淨的 - 例如,對於應該放置在該字典中的公開函數使用裝飾器;這種方式的元編程駭客很少。 –

回答

1

函數是python中的第一類公民,因此您可以將它們視爲普通變量,只需構建一個包含函數的列表即可:

>>> for f in [int, str, float]: 
...  for e in [10, "10", 10.0]: 
...   print(f(e)) 
...   
10 
10 
10 
10 
10 
10.0 
10.0 
10.0 
10.0 
1

如果你把你的有效protocol_func S的一套特定的模塊中,你可以使用getattr()從該模塊檢索:

import protocol_funcs 

protocol_func = getattr(protocol_funcs, function_name) 
threads.append(protocol_func(threadID, config.get(protocol, "port"))) 

另一種方法是註冊選項裝飾:

protocol_funcs = {} 

def protocol_func(f): 
    protocol_funcs[f.__name__] = f 
    return f 

...此後:

@protocol_func 
def some_protocol_func(id, port): 
    pass # TODO: provide a protocol function here 

這種方式只能用@protocol_func修飾的函數可以在配置文件中使用,並且該字典的內容可以平均迭代。

0

函數可以放在一個列表稍後調用:

def a(): 
    print("a") 
def b(): 
    print("b") 
def c(): 
    print("c") 
func = [a, b, c] 
for function in func: 
    function() 

你會得到的輸出是從所有的功能:

a 
b 
c 

使用相同的邏輯,讓您的代碼按預期工作

相關問題