python 模塊重載的五種方法
新建一個 foo 文件夾,其下包含一個 bar.py 文件
$ tree foofoo└── bar.py0 directories, 1 file
bar.py 的內(nèi)容非常簡單,只寫了個 print 語句
print('successful to be imported')
只要 bar.py 被導(dǎo)入一次,就被執(zhí)行一次 print
禁止重復(fù)導(dǎo)入由于有 sys.modules 的存在,當(dāng)你導(dǎo)入一個已導(dǎo)入的模塊時,實(shí)際上是沒有效果的。
>>> from foo import barsuccessful to be imported>>> from foo import bar>>>重載模塊方法一
如果你使用的 python2(記得前面在 foo 文件夾下加一個 __init__.py),有一個 reload 的方法可以直接使用
>>> from foo import barsuccessful to be imported>>> from foo import bar>>>>>> reload(bar)successful to be imported<module ’foo.bar’ from ’foo/bar.pyc’>
如果你使用的 python3 那方法就多了,詳細(xì)請看下面
重載模塊方法二如果你使用 Python3.0 -> 3.3,那么可以使用 imp.reload 方法
>>> from foo import barsuccessful to be imported>>> from foo import bar>>>>>> import imp>>> imp.reload(bar)successful to be imported<module ’foo.bar’ from ’/Users/MING/Code/Python/foo/bar.py’>
但是這個方法在 Python 3.4+,就不推薦使用了
<stdin>:1: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module’s documentation for alternative uses重載模塊方法三
如果你使用的 Python 3.4+,請使用 importlib.reload 方法
>>> from foo import barsuccessful to be imported>>> from foo import bar>>>>>> import importlib>>> importlib.reload(bar)successful to be imported<module ’foo.bar’ from ’/Users/MING/Code/Python/foo/bar.py’>重載模塊方法四
如果你對包的加載器有所了解
還可以使用下面的方法
>>> from foo import barsuccessful to be imported>>> from foo import bar>>>>>> bar.__spec__.loader.load_module()successful to be imported<module ’foo.bar’ from ’/Users/MING/Code/Python/foo/bar.py’>重載模塊方法五
既然影響我們重復(fù)導(dǎo)入的是 sys.modules,那我們只要將已導(dǎo)入的包從其中移除是不是就好了呢?
>>> import foo.barsuccessful to be imported>>>>>> import foo.bar>>>>>> import sys>>> sys.modules[’foo.bar’]<module ’foo.bar’ from ’/Users/MING/Code/Python/foo/bar.py’>>>> del sys.modules[’foo.bar’]>>>>>> import foo.barsuccessful to be imported
有沒有發(fā)現(xiàn)在前面的例子里我使用的都是 from foo import bar,在這個例子里,卻使用 import foo.bar,這是為什么呢?
這是因?yàn)槿绻闶褂?from foo import bar 這種方式,想使用移除 sys.modules 來重載模塊這種方法是失效的。
這應(yīng)該算是一個小坑,不知道的人,會掉入坑中爬不出來。
>>> import foo.barsuccessful to be imported>>>>>> import foo.bar>>>>>> import sys>>> del sys.modules[’foo.bar’]>>> from foo import bar>>>
以上就是python 模塊重載的五種方法的詳細(xì)內(nèi)容,更多關(guān)于python 模塊重載的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法2. Springboot 全局日期格式化處理的實(shí)現(xiàn)3. 利用CSS制作3D動畫4. .Net加密神器Eazfuscator.NET?2023.2?最新版使用教程5. jsp+servlet簡單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))6. JAMon(Java Application Monitor)備忘記7. 完美解決vue 中多個echarts圖表自適應(yīng)的問題8. SpringBoot+TestNG單元測試的實(shí)現(xiàn)9. 存儲于xml中需要的HTML轉(zhuǎn)義代碼10. idea配置jdk的操作方法
