Python: Sharing global variables between modules and classes therein

后端 未结 5 1347
不知归路
不知归路 2020-11-28 06:00

I know that it\'s possible to share a global variable across modules in Python. However, I would like to know the extent to which this is possible and why. For example,

5条回答
  •  孤城傲影
    2020-11-28 06:52

    This happens because you are using immutable values (ints and None), and importing variables is like passing things by value, not passing things by reference.

    If you made global_mod.x a list, and manipulated its first element, it would work as you expect.

    When you do from global_mod import x, you are creating a name x in your module with the same value as x has in global_mod. For things like functions and classes, this works as you would expect, because people (generally) don't re-assign to those names later.

    As Alex points out, if you use import global_mod, and then global_mod.x, you will avoid the problem. The name you define in your module will be global_mod, which always refers to the module you want, and then using attribute access to get at x will get you the latest value of x.

提交回复
热议问题