Examples of dynamic analytic function call python

  1. The dynamic call method eval string name within the python file ( "function_name") (parameter)

  2. The dynamic invocation string class static method, getattr (ClassName, "function_name") (parameter)

  3. apply (functoin_name, parameters) This is not a string function_name, but the function of the object itself; Parameters Parameter is similar (a, b, ...) in the format

  4. When the number of times a function of the uncertain parameters, using a two ** * or their usage is luxurious.

The following example is a list of functions defined dictionary, the dictionary contains the parameter function objects and functions may be dynamically added to the dictionary function is performed, the last performed together

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

We recommend the python learning sites to see how seniors are learning! From basic python script, reptiles, django, data mining, programming techniques, as well as to combat zero-based sorting data items, given to every love learning python small partner! Python veteran day have to explain the timing of technology, to share some of the ways to learn and need to pay attention to small details, click on Join us python learner gathering

Released three original articles · won praise 0 · Views 856

Guess you like

Origin blog.csdn.net/haoxun07/article/details/104450716