Python Basics Tutorial: Five Methods of Module Overloading

Environmental preparation

Create a new foo folder with a bar.py file under it

$ tree foo
foo
└── bar.py

0 directories, 1 file

The content of bar.py is very simple, just write a print statement

print("successful to be imported")

As long as bar.py is imported once, a print is executed

Duplicate import is prohibited

Because of the existence of sys.modules, when you import an imported module, it actually has no effect.

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

Repeat import method one

If you are using python2 (remember to add a __init__.py to the foo folder), there is a reload method that can be used directly

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:660193417
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> 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'>

If you use python3, there are more methods, please see below for details

Repeat import method 2

If you use Python3.0 -> 3.3, then you can use imp.reload method

>>> 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'>

But this method is deprecated in Python 3.4+

<stdin>:1: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses

Repeat import method three

If you are using Python 3.4+, please use the importlib.reload method

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:660193417
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> 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'>

Repeat import method five

Since it is sys.modules that affects our repeated import, can we just remove the imported package from it?

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:660193417
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> 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

おすすめ

転載: blog.csdn.net/m0_67575344/article/details/124150474