python - 如何从另一个模块的对象中更改模块变量的值?

标签 python

总结:我有一个公开(1) dict 的脚本我需要修改这个 dict来自另一个模块

注意:similar question 的两个很好的答案解释了很多关于模块之间的变量范围,但我不明白这如何适用于我的情况。

在下面的代码中,我预计我将能够修改 mainmodule.py变量 container来自内部submodule.py ,事实并非如此。为什么?

我应该如何解决 mainmodule container 的实例来自内部submodule

主脚本的代码

# mainmodule.py
# the main script which ultimately exposes the module variable 'container'
import submodule

container = dict()

class MainClass:
    def __init__(self):
        self.sub = submodule.SubClass()

    def set(self, number):
        print("main: container was {container}".format(container=container))
        container['x'] = number
        print("main: container is {container}".format(container=container))


    def call(self, number):
        self.sub.set(number)

if __name__ == "__main__":
    mc = MainClass()
    # updating container from this script
    mc.set(1)
    # updating container from another module
    mc.call(2)
    # again from this script, to check the updates
    mc.set(3)

导入模块的代码

# submodule.py
import mainmodule

class SubClass:
    def __init__(self):
        pass

    def set(self, number):
        print("sub: container was {container}".format(container=mainmodule.container))
        mainmodule.container['x'] = number
        print("sub: container is {container}".format(container=mainmodule.container))

输出是

main: container was {}
main: container is {'x': 1}
sub: container was {}
sub: container is {'x': 2}
main: container was {'x': 1}
main: container is {'x': 3}

(1)实际代码使用bottle提供container通过json.dumps()

最佳答案

盯着你的代码看了一会儿,我想我知道是什么让你失望了。作为 python foo.py 调用的 python 脚本最终将成为一个名为 __main__ 的模块(在 sys.modules 中)。这意味着您的 mainmodule.py 显示的底部位被加载、编译和运行一次,其中 __name__ == "__main__",这会导致一些事情发生。该模块导入尚未导入的 submodule,以便加载并运行。

submodule 依次尝试导入 mainmodule。尽管该文件之前已执行过,但解释器并不知道该模块名称,因此 mainmodule.py 再次运行,这次使用 __name__ == "mainmodule" (这与 "__main__" 不同,因此跳过底部的 if 套件)。

这意味着您有两个 container 副本,一个在名为 __main__ 的模块中,另一个在名为 的模块中>主模块。两者都来自名为 ./mainmodule.py 的文件这一事实无关紧要。

有几种方法可以解决这个问题。一种是总是立即导入真实的,如:

# mainmodule.py
import submodule
class Foo:
    pass
if __name__ == "__main__":
    import mainmodule
    mainmodule.Foo()

另一种选择是将 if 中的代码移动到另一个文件。

关于python - 如何从另一个模块的对象中更改模块变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34594936/

相关文章:

python - 错误为 "invalid literal for int() with base 10"的查询字符串

python - 数据源用完时如何停止 Spark 流

Python:inspect.ismethod 如何工作?

python - 为什么 Python 会引发 TypeError 而不是 SyntaxError?

python - 多层感知器的 Keras 与 TensorFlow2 实现

python - PyQt 4 用户界面卡住

python - 制作从 python 中的类型通知的数据类对象派生的类工厂

python - 如何查找字符串中重复单词的位置 - Python

python - 我如何找到字符串中多个子字符串的位置(Python 3.4.3 shell)

Python numpy 排序一维数组