Skip to main content
 首页 » 编程设计

python之在 Python : changing value vs removing value inconsistency 中重新加载模块

2025年05月04日8lyhabc

在使用内置的 reload 调试一些代码时,我发现了一些不一致的行为。

考虑以下交互式 session :

Python 2.7.4 (default, Sep 26 2013, 03:20:26)  
[GCC 4.7.3] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import foo 
>>> foo.BAR 
'bar' 
>>> # here I edit foo.py, changing BAR to 'foobar' 
...  
>>> foo.BAR 
'bar' 
>>> # as expected 
...  
>>> reload(foo) 
<module 'foo' from 'foo.py'> 
>>> foo.BAR 
'foobar' 
>>> # as expected 
...  
>>>  

一切都按预期工作。但是,如果我删除该值而不是更改它,它就不会按预期工作

Python 2.7.4 (default, Sep 26 2013, 03:20:26)  
[GCC 4.7.3] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import foo 
>>> foo.BAR 
'bar' 
>>> # here I edit foo.py, removing BAR from it 
...  
>>> foo.BAR 
'bar' 
>>> # as expected 
...  
>>> reload(foo) 
<module 'foo' from 'foo.py'> 
>>> foo.BAR 
'bar' 
>>> # ??? 
...  
>>>  

为什么会这样?有没有办法重新加载模块并避免该问题?

请您参考如下方法:

取自docs :

如果一个模块实例化了一个类的实例,重新加载定义该类的模块不会影响实例的方法定义——它们继续使用旧的类定义。派生类也是如此。

当一个模块被重新加载时,它的字典(包含模块的全局变量)被保留。名称的重新定义将覆盖旧定义,因此这通常不是问题。如果模块的新版本没有定义旧版本定义的名称,则保留旧定义