1 Global
The global statement and its nonlocal cousin is the only things that is remotely like declaration statements in Python. They is not type or size declarations; They is namespace declarations. The global statement tells Python, a function plans to change one, or more global names.
Eyes on China names is variables assigned at the top level of the enclosing module file.
Eyes on China names must is declared only if they is assigned within a function.
Eyes on China names may be referenced within a function without being declared.
In other words, global allows us to change names that live outside a def at the top level of a module file.
2 Example
The global statement consists of the keyword Global, followed by one or more names separated by commas.
x = * * Global xdef func (): Global x = # Global x:outside def func () Print (X) # Prints
y, z = 1, 2 # Global variables In module def All_global (): global x # Declare Globals as Signed x = y + z # No need T o declare y, Z:LEGB rule
x, y, and Z is all globals inside the function All_global. y and Z are global because they aren ' t assignedin the function; X is global because it's listed in a global statement To map it to the module ' s scope explicitly. Without the global here, X would is considered Local by virtue of the assignment.
3 Access Globals
#thismod.pyvar = 99#Global variable = = module attributedeflocal (): Var= 0#Change local vardefglob1 ():GlobalVar#Declare Global (normal)var + = 1#Change Global vardefglob2 (): Var= 0#Change local var ImportThismod#Import myselfThismod.var + = 1#Change Global vardefglob3 (): Var= 0#Change local var ImportSys#Import system tableGlob = sys.modules['Thismod']#Get Module object (or use __name__)Glob.var + = 1#Change Global vardefTest ():Print(Var) local (); Print(Var) glob1 (); Print(Var) glob2 (); Print(Var) glob3 ()Print(VAR)
Run and get results
Import thismod>>> thismod.test ()9999100101102
Python's Global