Python動態(tài)導入模塊:__import__、importlib、動態(tài)導入的使用場景實例分析
本文實例講述了Python動態(tài)導入模塊:__import__、importlib、動態(tài)導入的使用場景。分享給大家供大家參考,具體如下:
相關(guān)內(nèi)容: __import__ importlib 動態(tài)導入的使用場景首發(fā)時間:2018-02-23 16:06
__import__:功能: 是一個函數(shù),可以在需要的時候動態(tài)導入模塊使用: __import__(模塊名) 但對于多級目錄,只會導入第一級



mo1=__import__('des')mo2=__import__('child.child')mo3=__import__('child')print(mo1,mo2,mo3)#mo3與mo2相同#同級目錄使用模塊對象來調(diào)用mo1.B()mo1.fun2()#對于目錄下的,動態(tài)導入只會導入第一級目錄mo2.child.A()#雖然沒有具體定義類體,但無錯就是成功mo2.child.fun1()mo3.child.fun1()importlib:介紹: 是一個模塊,可以進行動態(tài)導入模塊用法: importlib.import_module('模塊名')
import importlibmo1= importlib.import_module(’des’)mo2= importlib.import_module(’child.child’)print(mo1,mo2)#mo2直接到child.childdes_B= mo1.B()mo1.fun2()mo2.fun1()動態(tài)導入模塊的使用場景: 動態(tài)切換模塊 使用反射判斷是否有對應(yīng)類、方法,無則設(shè)置
import importlibmo3= importlib.import_module(’child’)def func4(): print(' run in func4')if hasattr(mo3,'child1'): print('yes') c=getattr(mo3,'child')else: #沒有則設(shè)置 setattr(mo3,'func4',func4)mo3.func4() 其他。。。
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章:
1. 一個 2 年 Android 開發(fā)者的 18 條忠告2. Vue實現(xiàn)仿iPhone懸浮球的示例代碼3. js select支持手動輸入功能實現(xiàn)代碼4. vue-drag-chart 拖動/縮放圖表組件的實例代碼5. 什么是Python變量作用域6. Spring的異常重試框架Spring Retry簡單配置操作7. Android 實現(xiàn)徹底退出自己APP 并殺掉所有相關(guān)的進程8. PHP正則表達式函數(shù)preg_replace用法實例分析9. Android studio 解決logcat無過濾工具欄的操作10. vue使用moment如何將時間戳轉(zhuǎn)為標準日期時間格式
