Python: Sharing global variables between modules and classes therein

后端 未结 5 1349
不知归路
不知归路 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:40

    To solve this problem, just change from global_mod import * to import global_mod.

    And the new mid_access_mod.py will be:

    import global_mod
    
    class delta:
        def __init__(self):
            print global_mod.x
    

    The reason for that could be found here.

    Due to the way references and name binding works in Python, if you want to update some symbol in a module, say foo.bar, from outside that module, and have other importing code "see" that change, you have to import foo a certain way.

提交回复
热议问题