在python中如何使用变量作为函数名

在python中如何使用变量作为函数名,python,Python,如何使用变量作为函数名,这样我就可以有一个函数列表并在循环中初始化它们。我得到了我预期的错误,即str对象不可调用。但我不知道如何修复它。谢谢 #Open protocol configuration file config = configparser.ConfigParser() config.read("protocol.config") # Create new threads for each protocol that is configured protocols = ["ISO

如何使用变量作为函数名,这样我就可以有一个函数列表并在循环中初始化它们。我得到了我预期的错误,即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")

如果将一组有效的
protocol\u 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\u func
修饰的函数才能在配置文件中使用,字典的内容可以简单地迭代。

如果您将有效的
protocol\u 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
修饰的函数才能在配置文件中使用,并且该字典的内容可以简单地迭代。

函数可以放在一个列表中,以便以后调用:

def a():
    print("a")
def b():
    print("b")
def c():
    print("c")
func = [a, b, c]
for function in func:
    function()
您将获得的输出来自所有函数:

a
b
c

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

可以将函数放在稍后调用的列表中:

def a():
    print("a")
def b():
    print("b")
def c():
    print("c")
func = [a, b, c]
for function in func:
    function()
您将获得的输出来自所有函数:

a
b
c

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

函数是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

函数是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
这些功能在哪里?在特定模块中?当前模块?通常,将函数作为字典键并进行查找是最干净的——例如,对应该放在字典中的公开函数使用装饰器;更不用说那样的元编程黑客了。这些函数在哪里?在特定模块中?当前模块?通常,将函数作为字典键并进行查找是最干净的——例如,对应该放在字典中的公开函数使用装饰器;更不用说那样的元编程黑客了。