如何在Python中重新加载模块的功能? [英] How to reload a module's function in Python?
问题描述
跟进有关重新加载模块的问题 ,如何从更改的模块重新加载特定函数?
Following up on this question regarding reloading a module, how do I reload a specific function from a changed module?
伪代码:
from foo import bar
if foo.py has changed:
reload bar
推荐答案
您想要的是什么,但需要重新加载两件事......首先重新加载(foo)
,但是你还必须重新加载(baz)
(假设 baz
是包含该模块的模块的名称来自foo导入栏的
声明)。
What you want is possible, but requires reloading two things... first reload(foo)
, but then you also have to reload(baz)
(assuming baz
is the name of the module containing the from foo import bar
statement).
至于为什么......当 foo <首先加载/ code>,创建一个
foo
对象,其中包含 bar
对象。当您将 bar
导入 baz
模块时,它会存储对 bar的引用
。当调用 reload(foo)
时, foo
对象将被清空,模块将重新执行。这意味着所有 foo
引用仍然有效,但是已经创建了一个新的 bar
对象...所以所有引用都是已导入某处仍然是对旧 bar
对象的引用。通过重新加载 baz
,您可以重新导入新的栏
。
As to why... When foo
is first loaded, a foo
object is created, containing a bar
object. When you import bar
into the baz
module, it stores a reference to bar
. When reload(foo)
is called, the foo
object is blanked, and the module re-executed. This means all foo
references are still valid, but a new bar
object has been created... so all references that have been imported somewhere are still references to the old bar
object. By reloading baz
, you cause it to reimport the new bar
.
或者,您可以在模块中执行 import foo
,并始终调用 foo的.bar()
。这样,每当你重新加载(foo)
时,你将获得最新的栏
参考。
Alternately, you can just do import foo
in your module, and always call foo.bar()
. That way whenever you reload(foo)
, you'll get the newest bar
reference.
这篇关于如何在Python中重新加载模块的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!