怎么在python中动态调用函数

  介绍

这篇文章给大家介绍怎么在python中动态调用函数,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

1。根据字符串名称动态调用python文件内的方法eval (“function_name")(参数)

2。根据字符串动态调用类中的静态方法,getattr(名称,“function_name")(参数)

3。应用(functoin_name参数)这个function_name不是字符串,而是函数对象本身;参数是参数,类似(a, b,…)这样的格式

4。当函数不确定参数的数目时候,采用一个*或两个* *他们的用法是有讲究的。

下面的例子是,定义了一个函数列表字典,字典中保存有函数对象和函数的参数,可以实现动态为字典添加执行的函数,最后一起执行

得到collections  import  OrderedDict   ,   class  ComponentCheck:   def 才能;__init__(自我,,data_dir):   ,,,self.data_dir =data_dir   ,   ,,,self._extend_function_dic =, OrderedDict ({})   ,   def 才能;add_extend_function(自我,,function_name,, *参数):   ,,,self._extend_function_dic [function_name],=,参数   ,   def 才能_check_extend_function(自我):   ,,,for  function_name,, parameters 拷贝self._extend_function_dic.iteritems ():   ,,,,,if  not 应用(function_name,参数):   ,,,,,,,return 错误的   ,,,return 真实的   ,   class  CheckFunctions:   def 才能__init__(自我):   ,才能通过   ,   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中动态调用函数就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看的到。

怎么在python中动态调用函数