溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python中有哪些模塊重載的方法

發(fā)布時(shí)間:2021-04-30 15:27:34 來源:億速云 閱讀:116 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章為大家展示了python中有哪些模塊重載的方法,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

python有哪些常用庫

python常用的庫:1.requesuts;2.scrapy;3.pillow;4.twisted;5.numpy;6.matplotlib;7.pygama;8.ipyhton等。

環(huán)境準(zhǔn)備

新建一個(gè) foo 文件夾,其下包含一個(gè) bar.py 文件

$ tree foo
foo
└── bar.py

0 directories, 1 file

bar.py 的內(nèi)容非常簡單,只寫了個(gè) print 語句

print("successful to be imported")

只要 bar.py 被導(dǎo)入一次,就被執(zhí)行一次 print

禁止重復(fù)導(dǎo)入

由于有 sys.modules 的存在,當(dāng)你導(dǎo)入一個(gè)已導(dǎo)入的模塊時(shí),實(shí)際上是沒有效果的。

>>> from foo import bar
successful to be imported
>>> from foo import bar
>>>

重載模塊方法一

如果你使用的 python2(記得前面在 foo 文件夾下加一個(gè) __init__.py),有一個(gè) reload 的方法可以直接使用

>>> from foo import bar
successful 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 bar
successful 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'>

但是這個(gè)方法在 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 bar
successful 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 bar
successful 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.bar
successful 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.bar
successful to be imported

有沒有發(fā)現(xiàn)在前面的例子里我使用的都是 from foo import bar,在這個(gè)例子里,卻使用 import foo.bar,這是為什么呢?

這是因?yàn)槿绻闶褂?from foo import bar 這種方式,想使用移除 sys.modules 來重載模塊這種方法是失效的。

這應(yīng)該算是一個(gè)小坑,不知道的人,會掉入坑中爬不出來。

>>> import foo.bar
successful to be imported
>>>
>>> import foo.bar
>>>
>>> import sys
>>> del sys.modules['foo.bar']
>>> from foo import bar
>>>

上述內(nèi)容就是python中有哪些模塊重載的方法,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI