1

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

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

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

结果应该是:函数被调用

4

3 回答 3

4

如果您愿意离开()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()
于 2013-06-18T09:44:25.897 回答
1

使用eval()

eval("fetch_function()")
于 2013-06-18T09:25:36.557 回答
0

如前所述 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']()
于 2013-06-18T09:49:00.463 回答