Scope Introduction
The scope in Python is divided into 4 cases: l:local, local scope, which is the variable defined in the function;
E:enclosing, the local scope of the nested parent function, which is the local scope of the ancestor function that contains the function, but not the global;
G:globa, a global variable, is a variable defined at the module level, b:built-in, a variable within the system's fixed module, such as int, ByteArray, etc. The order of precedence for a search variable is: scope local > Outer scope > Global >python Built-in scope in the current module, that is, LEGB.
x = Int (2.9) # int built-ing_count = 0 # Globaldef outer (): O_count = 1 # enclosingdef inner (): I_count = 2 # Local
Of course, local and enclosing are relative, and enclosing variables are local to the upper level.
#定义变量a >>> a = 0>>> print a0# define function P () >>> def p (): ... print a ... >>> p () 0# define function P2 () >&G t;> def p2 (): ... print a ... a = 3 ... Print a ... >>> p2 () # Run error, external variable A is referenced first, cannot be re-assigned Traceback (most recent called last): File "
", line 1, in
File "
", Line 2, in p2unboundlocalerror:local variable ' a ' referenced before assignment# define function p3 ( ) >>> def p3 (): ... a = 3 # does not refer to direct assignment ... print a ... >>> p3 () 3>>> Print A0 # external variable
A does not change
The above is a small series to introduce you to the Python variables and scope of the detailed, if you have any questions please give me a message, small series will promptly reply to everyone. Thank you very much for the support of the Scripting House website!