The order in which Python references variables: current scope local variables, outer scope variables, global variables in current module->python built-in variables
First, global
The global keyword is used to use globals in functions or other local scopes. However, if you do not modify global variables, you can not use the Global keyword.
Copy the Code code as follows:
Gcount = 0
Def global_test ():
Print (Gcount)
Def global_counter ():
Global Gcount
Gcount +=1
Return Gcount
Def global_counter_test ():
Print (Global_counter ())
Print (Global_counter ())
Print (Global_counter ())
Second, nonlocal
The nonlocal keyword is used to use an outer (non-global) variable in a function or other scope.
Copy the Code code as follows:
Def make_counter ():
Count = 0
Def counter ():
nonlocal count
Count + = 1
return count
Return counter
Def make_counter_test ():
MC = Make_counter ()
Print (MC ())
Print (MC ())
Print (MC ())
You can also use generator to implement similar counter. As follows:
Copy the Code code as follows:
Def counter_generator ():
Count = 0
While True:
Count + = 1
Yield count
Def counter_generator_test ():
# below is for Python 3.x and works well
Citer = Counter_generator (). __iter__ ()
i = 0
while (I < 3):
Print (citer.__next__ ())
I+=1
Def counter_generator_test2 ():
#below code don ' t work
#because Next () function still suspends and cannot exit
#it seems the iterator is generated every time.
j = 0
For ITER in Counter_generator ():
while (J < 3):
Print (ITER)
J+=1