Using global variables between files?

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

    You can think of Python global variables as "module" variables - and as such they are much more useful than the traditional "global variables" from C.

    A global variable is actually defined in a module's __dict__ and can be accessed from outside that module as a module attribute.

    So, in your example:

    # ../myproject/main.py
    
    # Define global myList
    # global myList  - there is no "global" declaration at module level. Just inside
    # function and methods
    myList = []
    
    # Imports
    import subfile
    
    # Do something
    subfile.stuff()
    print(myList[0])
    

    And:

    # ../myproject/subfile.py
    
    # Save "hey" into myList
    def stuff():
         # You have to make the module main available for the 
         # code here.
         # Placing the import inside the function body will
         # usually avoid import cycles - 
         # unless you happen to call this function from 
         # either main or subfile's body (i.e. not from inside a function or method)
         import main
         main.mylist.append("hey")
    

提交回复
热议问题