我有一个名为 myfile.py
的模块
//myfile.py
msg = 'Hello World'
然后我导入它:import myfile
然后我做一些修改,比如:
//myfile.py (updated)
a = 'Some text'
b = 'Some other text'
然后我调用重新加载函数:
from imp import reload
reload(myfile)
现在当我运行:dir(myfile)
它显示当前模块重新加载的名称以及以前的(所有其他以前的导入/重新加载)
这是否意味着在导入/重新加载模块时,“所有”名称(甚至更新后省略的名称)都可单独用于外部世界?
最佳答案
When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem. If the new version of a module does not define a name that was defined by the old version, the old definition remains.
模块在重新加载之前不会被删除。模块的新代码在所有旧变量绑定(bind)仍然存在的情况下执行。新代码定义的任何名称都会替换旧绑定(bind),但新版本未定义的任何名称都保留其旧值。 This also applies in Python 2 .
关于python - 重新加载模块是否会更改先前导入/重新加载的模块中的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21965009/