python 動態調用函數

來源:互聯網
上載者:User

標籤:iter   ini   component   列表   log   pass   init   direct   art   

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 OrderedDictclass 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 Trueclass 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 動態調用函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.