In this chapter, we say the principle of variable name resolution: LEGB principle
1. When a function uses an unauthenticated variable name, Python searches 4 scopes, local scope (L), def or Lambda's local scope (E), global scope (G) > Built-in scope (B) in the previous layer structure And stop for the first time you find this variable name.
2. When a function assigns a value to a variable, it always creates or alters the variable name of the local scope, and the division is declared as a global
In Test, the first time we assign a value to X, we create the variable, and then we change the variable x, and if x is a global variable, it will look like this:
X= ' E F t efdad ' def Test (): print (x) print (ID (x)) #x =123 #print (x) #print (ID (x)) if __name__== ' __ Main__ ': Test ()
However, we need to be aware that the comment in the above code is not, if the comment is released, he will be an error, why?
X= ' E F t efdad ' def Test (): print (x) print (ID (x)) x=123 Print (x) print (ID (x)) if __name__== ' __ Main__ ': Test ()
Output:
>>> ================================ RESTART ================================>>> Traceback (most Recent: file "C:\Python34\test.py", line 9, <module> Test () file "C:\Python34\test.py" , line 3, in test
Did not find the local variable x, I think so, although the Py is an explanatory language, but he still need to compile into the PYc file to execute, but this process we do not see, in the process of compiling x has been identified as a local variable, and is no longer the module inside the global variable, so this will happen, So how do we fix it? We just need to add global X in front of the change X, and the following section of our global keyword will tell you more about
X= ' E F t efdad ' def Test (): print (x) print (ID (x)) Global x x=123 print (x) print (ID (x)) if __ name__== ' __main__ ': Test ()
Output:
Save the above code as test.py and then run it.
3. Assign a value to a variable outside of the function (at the top or idle of the module), the namespace of the local scope and module is the same
Summary: This chapter mainly briefly explains the LEGB principle of variable name resolution
This chapter is here, thank you.
------------------------------------------------------------------
Click to jump 0 basic python-Catalogue
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
0 Basic python-16.3 Variable name resolution: LEGB principle