问题描述
它似乎是Python的一个不变量(只要Python具有不变量)
模块在Python会话中最多执行一次。我有一个
相当古怪的例子打破了这个不变量:任何人都可以启发
我发生了什么事情?
--- test.py ---
import imptest
execfile(''subtest.py'',dict(__ name__ =''subtest.py''))
--- imptest.py ---
打印''Imptest进口''
--- subtest.py ---
导入imptest
---
$ python test.py
Imptest导入
Imptest进口
$
嗯。如果字典中省略了值__name__,或者它的
值至少不匹配''subtest。''则该消息仅打印
一次(例如,传递dict(__ name __ =''subtest'')会产生一个
导入消息)。
这两种情况都发生在python 2.4和2.3。我不明白。
It seems to be an invariant of Python (insofar as Python has invariants)
that a module is executed at most once in a Python session. I have a
rather bizzare example that breaks this invariant: can anyone enlighten
me as to what is going on?
--- test.py ---
import imptest
execfile(''subtest.py'', dict(__name__ = ''subtest.py''))
--- imptest.py ---
print ''Imptest imported''
--- subtest.py ---
import imptest
---
$ python test.py
Imptest imported
Imptest imported
$
Hmm. If the value __name__ is omitted from the dictionary, or if its
value doesn''t match at least ''subtest.'' then the message is printed only
once (for example, passing dict(__name__=''subtest'') produces one
"imported" message).
This happens with both python 2.4 and 2.3. I don''t get it.
推荐答案
这篇关于导入时模块执行两次!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!