Contact Python time is not long, some knowledge points, the mastery is not very solid, I personally more advocating no matter what to learn, first of all must go back to the foundation to hit the very solid, and then go to the high place. Today encountered a Python global variables related operations, encountered a problem, so, here will own problems, do a record, to Long remember heart!!!
The use of global variables in Python, in fact, is not a wise choice, but I still believe that the existence is reasonable, is how you use; Global variables reduce the commonality between modules and functions, so you should try to avoid using global variables in the future programming process.
Use of global variables:
Method One:
In order to facilitate the management of the code, the global variables are uniformly put into a module, and then when using global variables, the global variable module is imported, and the global variables are used in this way;
To define a global variable in a module:
Copy the Code code as follows:
#global. py
Global_1 = 1
Global_2 = 2
Global_3 = ' Hello world '
Then import the global variable definition module in a module and use the global variable 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 Two:
Define the global variable directly in the module and then use it directly in the function to OK. However, when using global variables, you must identify them with the global keyword in the function:
Copy the Code code as follows:
CONSTANT = 0
Def modifyglobal ():
Global CONSTANT
Print (CONSTANT)
CONSTANT + = 1
if __name__ = = ' __main__ ':
Modifyglobal ()
Print (CONSTANT)
Complete explanation!!!