当你导入一个模块,然后再次导入它时,它会被重新导入/覆盖,还是被跳过? 当您导入模块“a”和“b”,同时在模块“a”中导入模块“b”时,会发生什么?这样做安全吗?例如,如果模块“b”中有一个实例化的类,您最终会实例化它两次吗?
最佳答案
import
加载匹配的 .py
、.pyc
或 .pyo
文件,创建模块对象,并将其连同完全限定(“虚线”)名称一起存储在 sys.modules
字典中。如果第二个 import
在此字典中找到要导入的模块,它将返回它而不会再次加载文件。
回答您的问题:
When you import a module, then reimport it again, will it get reimported/overwritten, or skipped?
它将被跳过。要明确地重新导入模块,请使用 reload()
内置函数。
When you import module "a" and "b", but also have module "b" imported in module "a", what happens?
import a
将从a.py[c]
加载a
,import b
将返回模块sys.modules['b']
已由 a
加载。
Is it safe to do this?
是的,绝对。
For example if that module "b" has a class instantiated in it, will you end up instantiating it twice?
没有。
关于python - Python 的 "import"内部是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8358258/