python 動態調用函數


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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM