add = lambda a, b: a + b # 判断成功 if(hasattr(add, '__call__')): print add(1,2)
# 判断成功 if(callable(add)): print add(2, 2)
from inspect import isfunction # 判断成功 if(isfunction(add)): print add(5, 5)
def fun(): print('hello') a = 'fun' # 判断函数是否存在 print(callable(eval(a),'__call__')) > True # 调用函数 eval(a)() > hello
应用示例:
def fun1(msg): print(1,msg.get('info')) def fun2(msg): print(2,msg.get('info')) def fun3(msg): print(3,msg.get('info')) msg = {'type':1,'info':'111'} fun_name = 'fun'+str(msg.get('type')) if callable(eval(fun_name),'__call__'): eval(fun_name)(msg) else: raise Exception('not found function')
这样就可以根据消息类型调用不同的处理函数
上一篇:45个实用的前端开发工具汇总
评论列表
发表评论
热评文章
相关阅读