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



mo1=__import__('des')mo2=__import__('child.child')mo3=__import__('child')print(mo1,mo2,mo3)#mo3與mo2相同#同級(jí)目錄使用模塊對(duì)象來調(diào)用mo1.B()mo1.fun2()#對(duì)于目錄下的,動(dòng)態(tài)導(dǎo)入只會(huì)導(dǎo)入第一級(jí)目錄mo2.child.A()#雖然沒有具體定義類體,但無錯(cuò)就是成功mo2.child.fun1()mo3.child.fun1()importlib:介紹: 是一個(gè)模塊,可以進(jìn)行動(dòng)態(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()動(dòng)態(tài)導(dǎo)入模塊的使用場(chǎng)景: 動(dòng)態(tài)切換模塊 使用反射判斷是否有對(duì)應(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)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章:
1. HTML DOM setInterval和clearInterval方法案例詳解2. WML語言的基本情況3. 使用css實(shí)現(xiàn)全兼容tooltip提示框4. CSS hack用法案例詳解5. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案6. css代碼優(yōu)化的12個(gè)技巧7. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)8. 使用純HTML的通用數(shù)據(jù)管理和服務(wù)9. 告別AJAX實(shí)現(xiàn)無刷新提交表單10. css進(jìn)階學(xué)習(xí) 選擇符
