我想用函数名称字符串获取函数,例如。
class test(object):
def fetch_function():
print "Function is call"
#now i want to fetch function using string
"fetch_function()"
结果应该是:函数被调用
我想用函数名称字符串获取函数,例如。
class test(object):
def fetch_function():
print "Function is call"
#now i want to fetch function using string
"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()
:
eval("fetch_function()")
如前所述 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']()