ZhangZhihui's Blog  

Each module is loaded into memory only once during an interpreter session or during a program run, regardless of the number of times it is imported into a program. If multiple imports occur, the module’s code will not be executed again and again.

Suppose during an interactive session, you have imported a module, and the code of the module is changed while you are using these modules. You might want to use the updated module code by importing it again, but this is not possible since any imports that are done after the first import just use the already loaded module object, the module is not reloaded and its code is not executed again. You have to restart the interpreter session or execute the program again to reload the module. However, you can force a reload by using the reload function from the importlib module. This way we can get the updated version of the already loaded module without exiting the interpreter session.

>>> import module1

>>> from importlib import reload

>>> reload(module1)

复制代码
zzh@ZZHPC:/zdata/Github/python$ python
Python 3.12.3 (main, May 16 2024, 09:18:37) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import aaa
>>> f = aaa.Fraction(2, 3)
>>> print(f)
2/3
>>> str(f)
'2/3'
>>> f
<aaa.Fraction object at 0x76587b535b50>
>>> from importlib import reload

Added __repr__ for class Fraction.

>>> reload(aaa)
<module 'aaa' from '/zdata/Github/python/aaa.py'>
>>> f
<aaa.Fraction object at 0x76587b535b50>
>>> f = aaa.Fraction(2, 3)
>>> f
Fraction(2,3)
复制代码

reload的更新对已经存在的变量不起作用。

posted on   ZhangZhihuiAAA  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2023-07-30 Python - Modifying Lists/Dictionaries
2023-07-30 Python - Exception Shadowing
2023-07-30 Python - sorted() a tuple
2023-07-30 Python - Conditional Unpacking
2023-07-30 Python - List Anarchy
 
点击右上角即可分享
微信分享提示