1. 根據字符串名稱 動態調用 python文件內的方法eval("function_name")(參數)
2. 根據字符串 動態調用類中的靜態方法,getattr(ClassName,"function_name")(參數)
3. apply(functoin_name,parameters) 這個function_name不是字符串,而是函數對象本身;parameters是參數,類似(a,b,...)這樣的格式
4. 當函數不確定參數的數目時候,采用 一個 * 或兩個** 他們的用法是有講究的。http://blog.csdn.net/feisan/article/details/1729905
下面的例子是,定義了一個函數列表字典,字典中保存有函數對象和函數的參數,可以實現動態為字典添加執行的函數,最后一起執行
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
