这篇文章给大家介绍怎么在python中动态调用函数,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
1. 根据字符串名称 动态调用 python文件内的方法eval("function_name")(参数)
2. 根据字符串 动态调用类中的静态方法,getattr(ClassName,"function_name")(参数)
3. apply(functoin_name,parameters) 这个function_name不是字符串,而是函数对象本身;parameters是参数,类似(a,b,...)这样的格式
4. 当函数不确定参数的数目时候,采用 一个 * 或两个** 他们的用法是有讲究的。
下面的例子是,定义了一个函数列表字典,字典中保存有函数对象和函数的参数,可以实现动态为字典添加执行的函数,最后一起执行
from collections import OrderedDict
class ComponentCheck:
def __init__(self, data_dir):
self.data_dir = data_dir
self._extend_function_dic = OrderedDict({})
def add_extend_function(self, function_name, *parameters):
self._extend_function_dic[function_name] = parameters
def _check_extend_function(self):
for function_name, parameters in self._extend_function_dic.iteritems():
if not apply(function_name, parameters):
return False
return True
class CheckFunctions:
def __init__(self):
pass
def tollcost_check(data_path):
toll_cost_path = os.path.join(data_path, Importer.DT_KOR_TOLL_COST)
tollcost_component = ComponentCheck(toll_cost_path)
tollcost_component.add_extend_function(tollcost_component.check_file_pattern_list_match, CheckFunctions.TOLL_COST_FILENAME_PATTERN)
return tollcost_component
@staticmethod
def speed_camera_check(data_path):
speed_camera_path = os.path.join(data_path, Importer.DT_SAFETY_CAMERA)
speed_camera_component = ComponentCheck(speed_camera_path)
speed_camera_component.add_extend_function(speed_camera_component.check_not_exist_empty_directory)
return speed_camera_component
关于怎么在python中动态调用函数就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。