Python Variables and scopes

Source: Internet
Author: User

1. 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.

?
1234567 x = int ( 2.9 )   # Code class= "Java keyword" >int built-in  g_ Count = 0   # Global def outer ():      o_count = 1   # enclosing      def inner ():           i_count = 2   # local

Of course, local and enclosing are relative, and enclosing variables are local to the upper level.
2. Scope Generation
In Python, only modules, classes, and functions (Def, Lambda) introduce new scopes, and other blocks of code (such as if, try, for, and so on) do not introduce new scopes, as in the following code:

?
1234 ifTrue:    x = 1;print(x)# 1

This is not a problem,if does not introduce a new scope, X is still in the current scope, the following code can be used.

?
1234 def test():    x2 = 2print(x2)# NameError: name ‘x2‘is not defined

Def, class, and lambda can be introduced into a new scope.
3. Modification of Variables
A variable that is not in the local scope is read-only by default, and if an attempt is made to bind a new value to it, Python believes that a new variable is created in the current local scope, that is, in the current local scope, if the variable of the outer scope is used directly, then the variable is read-only, Cannot be modified , such as:

?
1234567 count = 10def outer():    print(count)      count = 100    print(count)outer()#UnboundLocalError: local variable ‘count‘referenced before assignment


Here in the first print, the count of the outer scope is used, so that after count is the count in the outer scope, the modification will be an error. If you have not used this variable, and you assign it directly, it will be considered a newly defined variable, overwriting variables in the outer scope, such as:

?
123456 count = 10def outer():    count = 100    print(count)outer()#100

The count=100 is declared directly in the internal scope, and the subsequent use of count is the internal scope.
4. Global keywords
The Global and nonlocal keywords are used when the internal scope wants to modify the variables of the outer scope, and when the modified variable is on the global scope (the globally scope), use global first to declare the code as follows:

?
123456789 count = 10 def outer ():      Code class= "Java plain" >global count       print (count)         count = 100      print (count) outer () # 10 # 100


5. nonlocal Key Words
The variables declared by the Global keyword must be on the global scope, not nested scopes, and when you want to modify the variables in the nested scope (enclosing scope, outer non-global scope), then you need to nonlocal the keyword.

?
1234567891011 def outer():    count = 10    def inner():        nonlocal count        count = 20        print(count)    inner()    print(count)outer()#20#20



6. Summary
(1) variable lookup order: LEGB, scope local > Outer scope > Global >python Built-in scope in the current module, (2) only modules, classes, and functions can introduce new scopes; (3) for a variable, The inner scope declares the outer variable, does not declare it, uses the outer scope of the variable, and (4) The internal scope uses the Global keyword to modify the value of the outer scope variable, and the nested scope variable uses the nonlocal keyword. nonlocal is the python3 new keyword, with this keyword, you can achieve the perfect closure.

Python Variables and scopes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.