Python global variable operation details

  • 2020-05-09 18:48:08
  • OfStack

I haven't been in touch with Python for a long time, and I don't have a solid grasp of some knowledge points. I personally believe that no matter what I learn, I should first go back to lay a solid foundation and then go higher. Today, I encountered some related operations of global variables in Python and encountered some problems. Therefore, I will make a record of my problems here and keep a long memory!!

Using global variables in Python is, in my opinion, not a very wise choice. But I still believe that it is reasonable to exist, depending on how you use it; Global variables reduce the generality between modules and functions; Therefore, in the future programming process, should avoid using global variables as much as possible.

Use of global variables:

Method 1:

In order to facilitate code management, global variables are put into one module, and then when global variables are used, the global variable module is imported, and global variables are used in this way.
Define global variables in 1 module:


#global.py 
GLOBAL_1 = 1 
GLOBAL_2 = 2 
GLOBAL_3 = 'Hello World' 

Then import the global variable to define the module in one module, and use the global variable in the new module:

import globalValues 
 
def printGlobal(): 
    print(globalValues.GLOBAL_1) 
    print(globalValues.GLOBAL_3) 
    globalValues.GLOBAL_2 += 1 # modify values 
 
if __name__ == '__main__': 
    printGlobal() 
    print(globalValues.GLOBAL_2) 

Method 2:

Define global variables directly in a module, and then use ok directly in a function. However, when using global variables, the function must be identified using the global keyword:


CONSTANT = 0 
 
def modifyGlobal(): 
    global CONSTANT 
    print(CONSTANT) 
    CONSTANT += 1 
 
if __name__ == '__main__': 
    modifyGlobal() 
    print(CONSTANT) 

End of explanation!!


Related articles: