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__(模塊名)
- 但對于多級目錄,只會導入第一級
- 目錄結(jié)構(gòu):
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 importlib mo1= importlib.import_module('des') mo2= importlib.import_module('child.child') print(mo1,mo2)#mo2直接到child.child des_B= mo1.B() mo1.fun2() mo2.fun1()
動態(tài)導入模塊的使用場景:
- 動態(tài)切換模塊
- 使用反射判斷是否有對應類、方法,無則設(shè)置
import importlib mo3= 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)文章
Python使用cx_Oracle庫連接Oracle數(shù)據(jù)庫指南
這篇文章主要為大家介紹了Python使用cx_Oracle庫連接Oracle數(shù)據(jù)庫指南,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12Python3.5內(nèi)置模塊之random模塊用法實例分析
這篇文章主要介紹了Python3.5內(nèi)置模塊之random模塊用法,結(jié)合實例形式分析了Python3.5 random模塊生成隨機數(shù)與隨機字符串相關(guān)操作技巧,需要的朋友可以參考下2019-04-04