首页 > 编程 > Python > 正文

Python 由字符串函数名得到对应的函数(实例讲解)

2019-11-25 15:57:01
字体:
来源:转载
供稿:网友

把函数作为参数的用法比较直观:

def func(a, b): return a + bdef test(f, a, b):  print f(a, b)test(func, 3, 5)

但有些情况下,‘要传递哪个函数'这个问题事先还不确定,例如函数名与某变量有关。

可以利用 func = globals().get(func_name) 来得到函数:

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: yearfunc_month: month"""

以上这篇Python 由字符串函数名得到对应的函数(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表