Using global variables between files?

前端 未结 7 1490
轻奢々
轻奢々 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

    Hai Vu answer works great, just one comment:

    In case you are using the global in other module and you want to set the global dynamically, pay attention to import the other modules after you set the global variables, for example:

    # settings.py
    def init(arg):
        global myList
        myList = []
        mylist.append(arg)
    
    
    # subfile.py
    import settings
    
    def print():
        settings.myList[0]
    
    
    # main.py
    import settings
    settings.init("1st")     # global init before used in other imported modules
                             # Or else they will be undefined
    
    import subfile    
    subfile.print()          # global usage
    

提交回复
热议问题