python - 如何使用字符串获取函数?

标签 python

我想获取带有函数名字符串的函数 例如。

class test(object):
  def fetch_function():
    print "Function is call"

 #now i want to fetch function  using  string 
 "fetch_function()"

结果应该是:Function is call

最佳答案

如果您要从 fetch_function() 中保留 (),您可以使用 getattr,我认为这比 eval 更安全:

class Test(object):

    def fetch_function():
        print "Function is called"

test_instance = Test()
my_func = getattr(test_instance, 'fetch_function')

# now you can call my_func just like a regular function:
my_func()

关于python - 如何使用字符串获取函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17165152/

相关文章:

python - GDB+Python : Determining target type

python - 如何让 IntelliJ 识别常见的 Python 模块?

python - Python 的问题是没有测试?

linux - Python/C++ 扩展。导入时,出现 undefined symbol 错误

python - 读取和写入 40GB CSV 时出现内存错误...我的泄漏在哪里?

Python 3 - 类型错误 : can only concatenate str (not "bytes") to str

Python:带有列表列表的 cTurtle

python - 删除换行返回

python - 转换 MySQL 查询以在 web2py DAL 中使用

python - 使用 super() 继承关键字参数,但只有在创建实例时指定时才会列出它们