Python global variable operation details, python global variable details
I have not been familiar with Python for a long time. I do not have a solid grasp of some knowledge points. I personally advocate that no matter what I want to learn, I must first go back to the basics and go to the heights. Today I encountered operations related to global variables in Python, and encountered problems. So here I will record my problems and keep a long record !!!
When using global variables in Python, I personally think it is not a wise choice; but I still firmly believe that it is reasonable to exist because of how you use it; global variables reduce the versatility between modules and functions. Therefore, we should avoid using global variables in future programming.
Use of global variables:
Method 1:
To facilitate code management, you can place global variables in a single module. Then, when using global variables, You can import them to the global variable module. In this way, you can use global variables;
Define global variables in a module:
Copy codeThe Code is as follows:
# Global. py
GLOBAL_1 = 1
GLOBAL_2 = 2
GLOBAL_3 = 'Hello world'
Then, import the global variable definition module into a module and use global variables in the new module:
Copy codeThe Code is as follows:
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 the module, and then use them directly in the function. However, when using global variables, you must use the global keyword in the function for identification:
Copy codeThe Code is as follows:
CONSTANT = 0
Def modifyGlobal ():
Global CONSTANT
Print (CONSTANT)
CONSTANT + = 1
If _ name _ = '_ main __':
ModifyGlobal ()
Print (CONSTANT)
The explanation is complete !!!