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ù)字轉(zhuǎn)換為字母的方法
本文詳細(xì)介紹了在 Python 中將數(shù)字轉(zhuǎn)換為字母的幾種常用方法,我們介紹了使用 chr() 函數(shù)、string 模塊和 ord() 函數(shù)等方法,并提供了示例代碼幫助你理解和應(yīng)用這些方法,感興趣的朋友跟隨小編一起看看吧2023-06-06
簡介Python設(shè)計模式中的代理模式與模板方法模式編程
這篇文章主要介紹了Python設(shè)計模式中的代理模式與模板方法模式編程,文中舉了兩個簡單的代碼片段來說明,需要的朋友可以參考下2016-02-02
多線程爬蟲批量下載pcgame圖片url 保存為xml的實現(xiàn)代碼
用Python寫的多線程爬蟲批量下載pcgame的圖片url并保存為xml格式,主要是邏輯代碼,喜歡的朋友可以測試下2013-01-01
用Python的Flask框架結(jié)合MySQL寫一個內(nèi)存監(jiān)控程序
這篇文章主要介紹了用Python的Flask框架結(jié)合MySQL些一個內(nèi)存監(jiān)控程序的例子,并且能將結(jié)果作簡單的圖形化顯示,需要的朋友可以參考下2015-11-11
python使用Matplotlib繪圖及設(shè)置實例(用python制圖)
Python matplotlib包可以畫各種類型的圖,功能非常齊全,下面這篇文章主要給大家介紹了關(guān)于python使用Matplotlib繪圖及設(shè)置的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05

