Python實(shí)現(xiàn)動(dòng)態(tài)加載模塊、類、函數(shù)的方法分析
本文實(shí)例講述了Python實(shí)現(xiàn)動(dòng)態(tài)加載模塊、類、函數(shù)的方法。分享給大家供大家參考,具體如下:
動(dòng)態(tài)加載模塊:
方式1:系統(tǒng)函數(shù)__import__()
方式2:imp, importlib 模塊
方式3:exec 函數(shù)
動(dòng)態(tài)加載類和函數(shù)
首先,使用加載模塊,使用內(nèi)置函數(shù)提供的反射方法getattr(),依次按照層級(jí)獲取模塊->類\全局方法->類對(duì)象\類方法。
test_import_module.py
class ClassA: def test(self): print('test') int_value = 1 str_value = __author__ # 全局方法,加載時(shí)會(huì)被調(diào)用 print(__file__, 'global function.') if __name__ == '__main__': print(__file__, __name__)
test_import_module.py
# 注意:模塊名不包括.py后綴 imp_module = 'test_import_class' imp_class = 'ClassA' # 方式1:使用__import__()導(dǎo)入模塊 # 導(dǎo)入指定模塊,導(dǎo)入時(shí)會(huì)執(zhí)行全局方法。 ip_module = __import__(imp_module) # dir()查看模塊屬性 print(dir(ip_module)) # 使用getattr()獲取imp_module的類 test_class = getattr(ip_module, imp_class) # 動(dòng)態(tài)加載類test_class生成類對(duì)象 cls_obj = test_class() # 查看對(duì)象屬性 print(dir(cls_obj)) for attr in dir(cls_obj): # 加載非__前綴的屬性 if attr[0] != '_': # 獲取導(dǎo)入obj方法。 class_attr_obj = getattr(cls_obj, attr) # 判斷類屬性是否為函數(shù) if hasattr(class_attr_obj, '__call__'): # 執(zhí)行函數(shù) class_attr_obj() else: # 輸出類屬性值 print(attr, ' type:', type(class_attr_obj), ' value:', class_attr_obj)
輸出結(jié)果
D:/work/python\test_import_class.py global function. ['ClassA', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__'] ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'int_value', 'str_value', 'test'] int_value type: <class 'int'> value: 1 str_value type: <class 'str'> value: abc test
# 方式2:使用importlib # importlib相比__import__(),操作更簡(jiǎn)單、靈活,支持reload() import importlib ip_module = importlib.import_module('.', imp_module) ip_module_cls = getattr(ip_module, imp_class) cls_obj = ip_module_cls() if 'int_value' in dir(cls_obj): print(cls_obj.int_value) cls_obj.int_value = 10 print(cls_obj.int_value) # reload()重新加載,一般用于原模塊有變化等特殊情況。 # reload()之前該模塊必須已經(jīng)使用import導(dǎo)入模塊。 # 重新加載模塊,但原來(lái)已經(jīng)使用的實(shí)例還是會(huì)使用舊的模塊,而新生產(chǎn)的實(shí)例會(huì)使用新的模塊,reload后還是用原來(lái)的內(nèi)存地址。 ip_module = importlib.reload(ip_module) print(getattr(ip_module, imp_class).int_value) # 循環(huán)多次加載相同文件,手動(dòng)修改文件數(shù)據(jù),發(fā)現(xiàn)重新加載后輸出內(nèi)容變更。 from time import sleep for i in range(30): ip_module = importlib.reload(ip_module) print(getattr(ip_module, imp_class).int_value) sleep(3)
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python編碼操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Python實(shí)戰(zhàn)之疫苗研發(fā)情況可視化
2020年底以來(lái),歐美,印度,中國(guó),俄羅斯等多國(guó)得制藥公司紛紛推出了針對(duì)新冠/肺炎的疫苗,這部分主要分析了2020年以來(lái)全球疫情形勢(shì),各類疫苗在全球的地理分布,疫苗在各國(guó)的接種進(jìn)度進(jìn)行可視化展示,需要的朋友可以參考下2021-05-05Python 調(diào)用 Windows API COM 新法
Python中調(diào)用Win32API 通常都是使用 PyWin32或者ctypes。本文給大家介紹Python 調(diào)用 Windows API COM 新法,感興趣的朋友跟隨小編一起看看吧2019-08-08pycharm debug 斷點(diǎn)調(diào)試心得分享
這篇文章主要介紹了pycharm debug 斷點(diǎn)調(diào)試心得分享,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-04-04Python基于time模塊求程序運(yùn)行時(shí)間的方法
這篇文章主要介紹了Python基于time模塊求程序運(yùn)行時(shí)間的方法,涉及Python time模塊的使用及數(shù)值運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2017-09-09python中報(bào)錯(cuò)"json.decoder.JSONDecodeError: Expecting value:"的解決
這篇文章主要介紹了python中報(bào)錯(cuò)"json.decoder.JSONDecodeError: Expecting value:"的解決方法 ,需要的朋友可以參考下2019-04-04利用Python的pandas數(shù)據(jù)處理包將寬表變成窄表
這篇文章主要介紹了利用Python的pandas數(shù)據(jù)處理包將寬表變成窄表,文章通過(guò)圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09Python實(shí)現(xiàn)一個(gè)簡(jiǎn)單的驗(yàn)證碼程序
這篇文章主要介紹了Python實(shí)現(xiàn)一個(gè)簡(jiǎn)單的驗(yàn)證碼程序,具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11Python實(shí)現(xiàn)簡(jiǎn)單的列表冒泡排序和反轉(zhuǎn)列表操作示例
這篇文章主要介紹了Python實(shí)現(xiàn)簡(jiǎn)單的列表冒泡排序和反轉(zhuǎn)列表操作,涉及Python列表遍歷、排序、追加等相關(guān)操作技巧,需要的朋友可以參考下2019-07-07