我想用函数名字符串获取函数 例如
class test(object):
def fetch_function():
print "Function is call"
#now i want to fetch function using string
"fetch_function()"
结果应该是:函数是调用
答案 0 :(得分: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()
答案 1 :(得分:1)
使用eval()
:
eval("fetch_function()")
答案 2 :(得分: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']()