如何在python中将变量用作函数名称

时间:2016-05-17 16:00:44

标签: python

如何将变量用作函数名,以便我可以拥有一个函数列表并在循环中初始化它们。我收到了我预期的错误,即str对象不可调用。但我不知道如何解决它。感谢。

#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")

3 个答案:

答案 0 :(得分:1)

如果您将一组有效的protocol_func放在特定模块中,则可以使用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修饰的函数,并且可以轻易地迭代该字典的内容。

答案 1 :(得分: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

答案 2 :(得分: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

使用相同的逻辑来使代码按预期工作

相关问题