how to have global variables among different modules in Python

好久不见. 提交于 2019-12-24 01:07:18

问题


I investigated that scope of global variables in python is limited to the module. But I need the scope to be global among different modules. Is there such a thing? I played around __builtin__ but no luck.

thanks in advance!


回答1:


You can access global variables from other modules by importing them explicitly.

In module foo:

  joe = 5

In module bar:

  from foo import joe
  print joe

Note that this isn't recommended, though. It's much better to hide access to a module's variables by using functions.




回答2:


Python does not support globals shared between several modules: this is a feature. Code that implicitly modifies variables used far away is confusing and unmaintainable. The real solution is to encapsulate all state within a class and pass its instance to anything that has to modify it. This can make code clearer, more maintainable, more testable, more modular, and more expendable.




回答3:


Scopes beyond the local must be written to via a reference to the scope, or after a global or nonlocal (3.x+) directive.



来源:https://stackoverflow.com/questions/2296550/how-to-have-global-variables-among-different-modules-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!