Python 由字符串函数名得到对应的函数(实例讲解)
把函数作为参数的用法比较直观:
1
2
3
4
5
6
7
def func(a, b):
return a + b
def test(f, a, b):
print f(a, b)
test(func, 3, 5)
但有些情况下,‘要传递哪个函数’这个问题事先还不确定,例如函数名与某变量有关。
可以利用 func = globals().get(func_name) 来得到函数:
Python客栈送红包、纸质书
1
2
3
4
5
6
7
8
9
10
11
12
13
14
def func_year(s):
print ‘func_year:’, s
def func_month(s):
print ‘func_month:’, s
strs = [‘year’, ‘month’]
for s in strs:
globals().get(‘func_%s’ % s)(s)
“”"
输出:
func_year: year
func_month: month
“”"
(完)