2016-05-17 184 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 

使用相同的逻辑,让您的代码按预期工作

相关问题