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

2024-03-28 20:22:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用函数名字符串获取函数 例如

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

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

结果应该是:函数是call


Tags: to函数字符串testobjectisdeffunction
3条回答

使用eval()

eval("fetch_function()")

如果你把()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()

正如前面所说的eval不安全,您可以使用dict将函数映射到字符串并调用它

class test(object):
  dict_map_func = {'fetch_f': fetch_function}
  def fetch_function():
     print "Function is call"


test.dict_map_func['fetch_f']()

相关问题 更多 >