Using global variables between files?

前端 未结 7 1685
轻奢々
轻奢々 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:14

    Your 2nd attempt will work perfectly, and is actually a really good way to handle variable names that you want to have available globally. But you have a name error in the last line. Here is how it should be:

    # ../myproject/main.py
    
    # Import globfile    
    import globfile
    
    # Save myList into globfile
    globfile.myList = []
    
    # Import subfile
    import subfile
    
    # Do something
    subfile.stuff()
    print(globfile.myList[0])
    

    See the last line? myList is an attr of globfile, not subfile. This will work as you want.

    Mike

提交回复
热议问题