Python 之模块重载的五种方法
python环境准备
新建一个foo文件夹,其下包含一个bar.py文件:
$treefoo
foo
└──bar.py
0directories,1file
bar.py的内容非常简单,只写了个print语句:
print("successfultobeimported")
只要bar.py被导入一次,就被执行一次print。
禁止重复导入由于有sys.modules的存在,当你导入一个已导入的模块时,实际上是没有效果的。
>>>fromfooimportbar
successfultobeimported
>>>fromfooimportbar
>>>
重载模块方法一
如果你使用的python2(记得前面在foo文件夹下加一个__init__.py),有一个reload的方法可以直接使用:
>>>fromfooimportbar
successfultobeimported
>>>fromfooimportbar
>>>
>>>reload(bar)
successfultobeimported
如果你使用的python3那方法就多了,详细请看下面。
重载模块方法二
如果你使用Python3.0->3.3,那么可以使用imp.reload方法:
>>>fromfooimportbar
successfultobeimported
>>>fromfooimportbar
>>>
>>>importimp
>>>imp.reload(bar)
successfultobeimported
但是这个方法在Python3.4+,就不推荐使用了。
:1:DeprecationWarning:theimpmoduleisdeprecatedinfavourofimportlib;seethemodule'sdocumentationforalternativeuses
重载模块方法三
如果你使用的Python3.4+,请使用importlib.reload方法:
>>>fromfooimportbar
successfultobeimported
>>>fromfooimportbar
>>>
>>>importimportlib
>>>importlib.reload(bar)
successfultobeimported
重载模块方法四
如果你对包的加载器有所了解,还可以使用下面的方法:
>>>fromfooimportbar
successfultobeimported
>>>fromfooimportbar
>>>
>>>bar.__spec__.loader.load_module()
successfultobeimported
重载模块方法五
既然影响我们重复导入的是sys.modules,那我们只要将已导入的包从其中移除是不是就好了呢?
>>>importfoo.bar
successfultobeimported
>>>
>>>importfoo.bar
>>>
>>>importsys
>>>sys.modules['foo.bar']
>>>delsys.modules['foo.bar']
>>>
>>>importfoo.bar
successfultobeimported
有没有发现在前面的例子里我使用的都是fromfooimportbar,在这个例子里,却使用importfoo.bar,这是为什么呢?
这是因为如果你使用fromfooimportbar这种方式,想使用移除sys.modules来重载模块这种方法是失效的。
这应该算是一个小坑,不知道的人,会掉入坑中爬不出来。
>>>importfoo.bar
successfultobeimported
>>>
>>>importfoo.bar
>>>
>>>importsys
>>>delsys.modules['foo.bar']
>>>fromfooimportbar
>>>
以上内容为大家介绍了Python之模块重载的五种方法,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。http://www.mobiletrain.org/

相关推荐HOT
更多>>
python正则表达式中的零宽断言
python正则表达式中的零宽断言1、概念有些元字符不匹配任何字符,只是简单的表示成功或失败,所以这些字符也叫零宽断言。2、符号举例(1)|或操作...详情>>
2023-11-14 11:35:03
python方法的绑定和未绑定
python方法的绑定和未绑定1、说明未绑定对象的方法:无self参数的方法,通过定义类调用函数,返回未绑定self的方法。绑定对象的方法:带self参...详情>>
2023-11-14 09:53:02
python海象运算符的使用
python海象运算符的使用1、在判断条件下允许操作。在一定程度上简化了代码,但降低了可读性。i=len((l:=[1,2,3]))#先对l进行赋值,在对i赋值whi...详情>>
2023-11-14 02:38:21
pythonelif语句报错是什么原因
python的else和elif语句也可以叫做子句,因为它们不能独立使用,两者都是出现在if、for、while语句内部的。else子句可以增加一种选择;而elif子...详情>>
2023-11-13 21:46:35热门推荐
技术干货






