When you run the file as a script, it is not considered to be the test
module. It is considered to be the __main__
module.
When execution hits import test
, a second execution of the file starts, where the module is considered to be test
.
When execution hits import test
again, Python recognizes that it's already importing test
and does not reexecute the module. Instead, it merely loads the half-initialized test
module object into the current namespace and continues on. Python's optimistic assumption is that you've written the code so that the contents of test
won't be needed until the import finishes.
When execution hits the assignments to test.a
and test.b
, that affects the test
module, but not __main__
, despite the fact that they came from the same file. Thus, the print a, b
from the imported module reflects the new values, while the print a, b
from __main__
reflects the initial values.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…