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



mo1=__import__('des')mo2=__import__('child.child')mo3=__import__('child')print(mo1,mo2,mo3)#mo3與mo2相同#同級目錄使用模塊對象來調(diào)用mo1.B()mo1.fun2()#對于目錄下的,動態(tài)導(dǎo)入只會導(dǎo)入第一級目錄mo2.child.A()#雖然沒有具體定義類體,但無錯就是成功mo2.child.fun1()mo3.child.fun1()importlib:介紹: 是一個模塊,可以進(jìn)行動態(tài)導(dǎo)入模塊用法: 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)導(dǎo)入模塊的使用場景: 動態(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ìn)階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章:
