简体   繁体   English

我有一个带有函数名称的字符串变量,如何在Python中调用该函数?

[英]i have a string variable which comes with function names, how do I call the function in Python?

I have a string variable which comes with different function names, and I have a file which contains an often different set of functions which matchs the content of the string, how do I call that function in Python? 我有一个带有不同函数名称的字符串变量,并且我有一个文件,其中包含一组经常与字符串内容匹配的函数,我该如何在Python中调用该函数?

Example: 例:

In File 1 在文件1中

def function1: ...
def function2: ...
def function3: ...

In File 2 在文件2中

functionname = "function2"

I need to call the function2 from the File1 from this file 我需要从此文件的File1中调用function2

myfunction = getattr(mymodule, functionname)
myfunction()

eval("function2")()

getattr(<module>, fname)()

name = 'function2'

assert re.match('^(?i)[_a-z][_a-z0-9]*$', name)

eval(name)()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM