Using global variables between files?

前端 未结 7 1634
轻奢々
轻奢々 2020-11-22 03:43

I\'m bit confused about how the global variables work. I have a large project, with around 50 files, and I need to define global variables for all those files.

What

7条回答
  •  春和景丽
    2020-11-22 04:18

    The problem is you defined myList from main.py, but subfile.py needs to use it. Here is a clean way to solve this problem: move all globals to a file, I call this file settings.py. This file is responsible for defining globals and initializing them:

    # settings.py
    
    def init():
        global myList
        myList = []
    

    Next, your subfile can import globals:

    # subfile.py
    
    import settings
    
    def stuff():
        settings.myList.append('hey')
    

    Note that subfile does not call init()— that task belongs to main.py:

    # main.py
    
    import settings
    import subfile
    
    settings.init()          # Call only once
    subfile.stuff()         # Do stuff with global var
    print settings.myList[0] # Check the result
    

    This way, you achieve your objective while avoid initializing global variables more than once.

提交回复
热议问题