<p>这个问题还不完全清楚,但我认为你误解了<a href="https://docs.python.org/2.7/library/functions.html#reload" rel="nofollow">^{<cd1>}</a>的作用。在</p>
<p>它重新导入模块,包括其中定义的所有新类对象,并更改<code>sys.modules[name]</code>以引用新的模块对象,还将名称复制到全局变量中。在</p>
<p>但这就是一切。它不会自动找到对旧模块的所有引用,更不用说旧模块中定义的任何内容,等等,并将它们全部修复为引用替换版本。(怎么可能?新模块中甚至可能没有替代版本。因此,如果您的值是由旧代码计算的,并且计算方式不同,那么会怎样;它必须重新运行导入模块后所做的所有操作。)</p>
<p>文档(上面的链接)用不同的术语解释了它,但是让我们把它具体化,这样我可以更直接地解释它。在</p>
<p>创建此文件:</p>
<pre><code># mod.py
class Spam(object):
def eggs(self):
print('spam spam spam spam')
</code></pre>
<p>现在:</p>
^{pr2}$
<p>现在编辑它:</p>
<pre><code># mod.py
class Spam(object):
def eggs(self):
print('out of spam!!!')
>>> reload(mod)
>>> spam.eggs()
spam spam spam spam
>>> morespam = mod.Spam()
>>> morespam.eggs()
out of spam!!!
>>> type(spam) is type(morespam)
False
</code></pre>
<p>当您通过调用<code>mod.Spam()</code>来创建<code>spam</code>,它在全局中查找<code>'mod'</code>,然后在结果模块中查找{<cd6>},然后调用其构造函数和初始值设定项,给您一个对象,该对象的<code>__class__</code>是对该<code>mod.Spam</code>类的引用。在</p>
<p>当您调用<code>spam.eggs()</code>时,Python在全局字典中查找<code>'spam'</code>,在<code>spam</code>对象的字典中查找{<cd11>},否则,在<code>spam.__class__</code>对象的字典中查找{<cd11>}。我们知道,这就是<code>mod.Spam</code>对象,它有一个<code>eggs</code>方法,因此被调用。在</p>
<p>现在,在我们<code>reload(mod)</code>之后,有一个名为<code>'mod'</code>的新对象,它有一个名为<code>'Spam'</code>的新类作为成员。但是旧的<code>mod</code>和<code>mod.Spam</code>对象,以及您的<code>spam</code>-仍然存在。而现有的<code>spam</code>在其<code>__class__</code>中仍然引用了旧的{<cd8>}。因此,当您第二次调用<code>spam.eggs()</code>时,与之前完全相同的情况发生。Python将<code>'spam'</code>作为全局查找,首先在<code>spam</code>中查找<code>'eggs'</code>,然后在{<cd14>}中查找{<cd11>},找到与之前相同的类,并调用与之前相同的函数。在</p>
<p>当我们再次调用<code>mod.Spam()</code>来构造<code>morespam</code>时,现在它在全局中查找<code>'mod'</code>,并找到新的{<cd5>}。然后在该模块中查找<code>'Spam'</code>,并找到新类。因此,我们有一个实例,它的<code>__class__</code>是新的<code>mod.Spam</code>。当我们调用它的<code>eggs</code>方法时,会发生与上面相同的情况,但现在调用的是新函数。在</p>
<hr/>
<p>使用<code>from mod import *</code>而不是{<cd40>}会使事情变得更难理解,但基本思想是相同的。<code>from mod import *</code>不会将<code>mod</code>放入全局变量,而是将其所有非私有全局变量(在<code>mod.__all__</code>中列出的任何内容,或者,如果不存在这样的内容,<code>mod</code>中不以一个下划线开头的任何内容)复制到全局变量。因此,<code>reload</code>创建一个新的模块对象,第二个<code>from mod import *</code>将新模块的所有非私有全局变量复制到全局变量中,替换旧的全局变量。但是您的<code>spam</code>实例仍然是旧的<code>Spam</code>的实例,而不是新实例。在</p>