Python 静态变量

发布于 2024-12-18 01:47:43 字数 1314 浏览 3 评论 0原文

我正在创建一个应用程序,它使用基类来保存所有配置值、导入方法等。

/
  - application.py
      + class foo
            + config = None
            + def loadconfig
  - otherfile.py
      + class bar
            + def getconfigvalue

因此,如果我启动 application.py 并且它运行 loadconfig ,它将一个值加载到 foo.config 中,然后导入(在所述函数内 - 以绕过循环导入)otherfile.py 并创建一个新的 bar< /code> 对象,然后尝试从中获取配置值foo.config,但表示 foo.config 等于 None。有什么建议吗?

简化代码:
ma​​in.py

class Main:
    config = None
    @staticmethod
    def start():
        ## Load the configuration from a file, creating a dict in Main.config ##
        Main.other()

    @staticmethod
    def other():
        from otherfile import otherclass
        otherclass()

Main.start()

otherfile.py

from main import Main
class otherclass:
    def __init__(self):
        print(Main.config) ## Prints "None"

注意:这样安排是因为它在程序中实际是这样工作的;我觉得它与范围有关

完整源文件:
asgard.py: http://pastebin.com/jRkWzrPq
库/childcontainer.py: http://pastebin.com/6a561Nun

I'm creating an application that uses a base class to hold all of the configuration values, import methods, etc.

/
  - application.py
      + class foo
            + config = None
            + def loadconfig
  - otherfile.py
      + class bar
            + def getconfigvalue

So, if I start application.py and it runs loadconfig, which loads a value into foo.config, and then imports (inside said function - to get around circular imports) otherfile.py and creates a new bar object, which then tries to get a configuration value from foo.config, but says that foo.config is equal to None. Any suggestions?

Simplified code:
main.py

class Main:
    config = None
    @staticmethod
    def start():
        ## Load the configuration from a file, creating a dict in Main.config ##
        Main.other()

    @staticmethod
    def other():
        from otherfile import otherclass
        otherclass()

Main.start()

otherfile.py

from main import Main
class otherclass:
    def __init__(self):
        print(Main.config) ## Prints "None"

Note: It was arranged like this because that's how it actually works in the program; I feel like it has something to do with scope

Full source files:
asgard.py: http://pastebin.com/jRkWzrPq
library/childcontainer.py: http://pastebin.com/6a561Nun

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半暖夏伤 2024-12-25 01:47:43

我将从我认为您的问题与 asgard 相关的内容开始工作,因为您的简化示例已损坏:

  1. 由于循环导入,您无法运行 main.py ,但我相信它是 main.py 您打算运行(运行 otherfile.py 不会出现我认为您遇到的问题)。
  2. 您实际上从未将任何内容分配给 Main.config。我不确定你打算分配给它的确切位置。

无论如何,请转到asgard.py

这里你遇到了模块__main__的问题。当你运行asgard.py时,它的__name____main__;您可能不知道的是,这实际上是它出现在 sys.modules 中的模块名称 - 主模块是 sys.modules['__main__'],不是 sys.modules['asgard']。然后,当您导入library.childcontainer时,它会尝试导入asgard。这会查找不存在的 sys.modules['asgard'],因此它将 asgard.py 的内容导入到新的模块对象中。

如果您有另一个文件 main.py ,它会 import asgard; asgard.Asgard.initialize() (忽略我下面提到的条件导入问题),您不会遇到此问题,因为 __main__ 模块将属于该 main。 pyasgard.py 只能以名称 asgard 导入。另一个可行的解决方案是 if __name__ == '__main__': sys.modules['asgard'] = sys.modules['__main__']。

请,不要永远拉出if __name__ == '__main__': import ...技巧。这意味着如果您尝试导入 asgard;例如,asgard.Asgard.initialize(),它将失败,提示名称“os”未定义。请将这些导入放在文件的顶部,也就是它们所属的位置。

I'll work from what I believe your issue is with asgard, because your simplified example is broken:

  1. You can't run main.py because of a circular import, yet I believe it was main.py you intended to be running (running otherfile.py won't exhibit the problem I believe you're running into).
  2. You're never actually assigning anything to Main.config. I'm not sure precisely where you were intending to assign to it.

Anyway, on to asgard.py.

Here you run into the problem of the module __main__. When you run asgard.py, its __name__ is __main__; something you may not be aware of is that this is literally its module name as it appears in sys.modules - the main module is sys.modules['__main__'], not sys.modules['asgard']. Then, when you import library.childcontainer, it tries to import asgard. This looks up sys.modules['asgard'], which doesn't exist, and so it imports the contents of asgard.py into a new module object.

If you were to have another file main.py which did import asgard; asgard.Asgard.initialize() (ignoring the conditional imports problem I mention below), you wouldn't run into this problem because the __main__ module would be of that main.py, and asgard.py would only ever be imported with the name asgard. Another solution which would work would be if __name__ == '__main__': sys.modules['asgard'] = sys.modules['__main__'].

And please, please, please don't ever pull that if __name__ == '__main__': import ... trick. This means that if you try to import asgard; asgard.Asgard.initialize(), for example, it will fail saying that the name 'os' is undefined. Please put these imports at the top of the file, where they belong.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文