python 動態(tài)調(diào)用函數(shù)實例解析
1. 根據(jù)字符串名稱 動態(tài)調(diào)用 python文件內(nèi)的方法eval("function_name")(參數(shù))
2. 根據(jù)字符串 動態(tài)調(diào)用類中的靜態(tài)方法,getattr(ClassName,"function_name")(參數(shù))
3. apply(functoin_name,parameters) 這個function_name不是字符串,而是函數(shù)對象本身;parameters是參數(shù),類似(a,b,...)這樣的格式
4. 當(dāng)函數(shù)不確定參數(shù)的數(shù)目時候,采用 一個 * 或兩個** 他們的用法是有講究的。
下面的例子是,定義了一個函數(shù)列表字典,字典中保存有函數(shù)對象和函數(shù)的參數(shù),可以實現(xiàn)動態(tài)為字典添加執(zhí)行的函數(shù),最后一起執(zhí)行
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
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Python函數(shù)遞歸調(diào)用實現(xiàn)原理實例解析
- Python基于字典實現(xiàn)switch case函數(shù)調(diào)用
- python怎么調(diào)用自己的函數(shù)
- python def 定義函數(shù),調(diào)用函數(shù)方式
- Python函數(shù)必須先定義,后調(diào)用說明(函數(shù)調(diào)用函數(shù)例外)
- 解決python調(diào)用自己文件函數(shù)/執(zhí)行函數(shù)找不到包問題
- python函數(shù)定義和調(diào)用過程詳解
- python關(guān)于調(diào)用函數(shù)外的變量實例
- python函數(shù)聲明和調(diào)用定義及原理詳解
- python通過函數(shù)名調(diào)用函數(shù)的幾種場景
相關(guān)文章
Python灰度變換中的分段線性函數(shù)專項分析實現(xiàn)
灰度變換是指根據(jù)某種目標條件按一定變換關(guān)系逐點改變源圖像中每個像素灰度值的方法。目的是改善畫質(zhì),使圖像顯示效果更加清晰。圖像的灰度變換處理是圖像增強處理技術(shù)中的一種非?;A(chǔ)、直接的空間域圖像處理方法,也是圖像數(shù)字化軟件和圖像顯示軟件的一個重要組成部分2022-10-10Python數(shù)據(jù)分析之Excel和Text文件的讀寫操作方法
Python操作Excel分為兩個主要形式,讀寫和交互式操作,可以用不同的第三方工具,下面這篇文章主要給大家介紹了關(guān)于Python數(shù)據(jù)分析之Excel和Text文件的讀寫操作方法,需要的朋友可以參考下2024-08-08Numpy中扁平化函數(shù)ravel()和flatten()的區(qū)別詳解
本文主要介紹了Numpy中扁平化函數(shù)ravel()和flatten()的區(qū)別詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02利用Python實現(xiàn)自動生成數(shù)據(jù)日報
日報,是大部分打工人繞不過的難題。對于管理者來說,日報是事前管理的最好抓手,可以了解團隊的氛圍和狀態(tài)。本文將利用Python實現(xiàn)自動生成數(shù)據(jù)日報,感興趣的可以動手嘗試一下2022-07-07