python variable scope, the closure

Look at the question:

  The output of the following code is 0, in other words, although this has been used fucn2 variable1 declared global, but did not change the value of variable

def func1():
    variable1=0
    def func2():
        global variable1
        variable1=2
    func2()
    print(variable1)
if __name__=="__main__":
    func1()

#下面这段代码也是输出0
variable1=0
def func1():
    variable1=0
    def func2():
        global variable1
        variable1=2
    func2()
    print(variable1)
if __name__=="__main__":
    func1()

  The output of the following code is 2, the function of the global

variable1=0
def func1():
    # variable1=0
    def func2():
        global variable1
        variable1=2
    func2()
    print(variable1)
if __name__=="__main__":
    func1()

  

Variable scope of knowledge involved:

 

Reference Links: https://www.jianshu.com/p/3bb277c2935c

    python variable scope Category:

  python variable scope in a total of four

  • The local scope (L: Local)

Local variables are defined and used within function variables, it is only effective within the function. After leaving function can no longer access the local variables, otherwise the interpreter will throw NameError error.

  • Closing the outer package function function (E: Enclosing)

Closed-defined package: If an internal function, the variables in the outer function (but not in the global scope) is referenced, then the internal function is considered to be closure (closure)

  • Global scope (G: Global)

Local variables and corresponding global variable is a variable means capable of acting on the internal and external functions, i.e., the global variables may be used outside the respective functions may be used within each function.

Definition of two ways: in vitro function defined variables, global variables must; variables defined in the global function in vivo. After that the use of global variables can be modified keyword, the variable will become global variables.

  • Built scopes (B: Built-in)

 

Some rules of variable scope

  In order to find different variables scope of variables

  To  L -> E -> G - > B  Rule find that: not found locally, it will go outside to find local topical (e.g., closure), you will not find to find the global, in addition to the built-in look.

  So there is no naming variables in python keyword conflict, but is there such a situation, the role of the duplicated variable domain

>>> str(2)
'2'
>>> str=5
>>> str
5
>>> str(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>>

  

  In addition this search sequence may also bring another problem: global variables and local variables shadowing phenomenon (when the same name myself)

  The default global variables may be accessed in all functions, but if the definition of the variables and the global variable in a function of the same name, then the local variable occurs shield (hide) the global variable case

. 1 = var 
DEF Fun (): 
    Print var 
    var = 200 is 
Print Fun () 

# file2.py 
var. 1 = 
DEF Fun (): 
    var = var +. 1 
    return var 
Print Fun () 
# Both functions given UnboundLocalError: local variable 'var' referenced before assignment

  Because inside, the interpreter function detects var be reassigned, and it has become a local variable var, but wanted to use var until they are assigned, this error will appear. The solution is to add an internal function  globals var but after running the function global var will be modified.

 

  python can change the code segment is variable scope def, class, lamda others such as:  if/elif/else/ try/except for/whiledoes not change its scope. Definition of variables within them, and still have access to the outside.

True if >>>: 
... = A 'the I AM A' 
... 
>>> A 
'the I AM A' 
# if variables defined in the language in which a, external or accessible. 
# But note that if if is def / class / lambda wrapped inside an assignment, it becomes a local scope function / class / lambda's.

  In the  def/class/lambdaconduct within the assignment, it becomes its local scope, local scope overrides the global scope, but will not affect the global scope.

 

Closure

  

  Closed-defined package: If an internal function, the variables in the outer function (but not in the global scope) is referenced, then the internal function is considered to be closure (closure)

  In the beginning of the problem, visit the func1 variable1 of func2 is a closure, A Python 3 has a keyword nonlocalcan solve this problem , but do not try to modify or Python2 the closure of variables.

def func1():
    variable1=0
    def func2():
        nonlocal variable1#这样就好了
        variable1=2
    func2()
    print(variable1)
if __name__=="__main__":
    func1()

 

  About a pit closures there:

Wraps functools Import from 

DEF warpper (log): 
    DEF External (F.): 
        @wraps (F.) 
        DEF Internal (** kW): 
            IF False: 
                log = 'Modified' 
            Print log 
        return Internal 
    return External 

@wrapper ( 'First') 
abc DEF (): 
    Pass 

Print abc () 
before referenced in the definition: # will appear nameerror

  The reason is that the interpreter to detect the if Falsere-assignment of, according to search rules variable , so it will not go the closure of the external function (Enclosing) in looking variables, but if Flasedoes not hold is not executed (so log assignment will be no execution that is not defined), so this error occurs. Unless you need else: log='var'or if Truebut such statements have no meaning to add logic (why did not the point?) , So try not to modify the closure of variables

  

Gets the specified range of variable scope

  Reference Links: http://c.biancheng.net/view/2259.html

  Whether or globally, a number of variables may exist on a local scale function, each variable "hold" value of the variable. From this perspective, whether it is local or global scope range, these variables and their values as an "invisible" in the dictionary, where the variable name is the dictionary key, the value of the variable is the dictionary value. In fact, Python  provides the following three tools function to get the "variable dictionary within the specified range ":

  1. globals (): This function returns all variables globally composition "variable dictionary."
  2. locals (): This function returns the current of all the local variables within range of the composition "variable dictionary."
  3. vars (object): Gets "variable dictionary" within a specified target range consisting of all variables. If no parameter passing object, action VARS () and about locals () are identical.

  

  globals () and locals () seems completely different, but they are actually linked, on the difference between these two functions and link to the following two points:

  • locals () always get the "Tag Dictionary" in the current local scope all variables consisting of, so if globally (outside the function) calls the locals () function, will also get "variable in the global scope of all variables consisting of Dictionary "; and globals () wherever execution, always get the global scope of all variables consisting of" variable dictionary. "
  • In general, using locals () and globals () Gets the "variable dictionary" should only be accessed, it should not be modified. But in fact, whether it is using globals () or using locals () won globally take the "variable dictionary", and can be modified, and this modification will really change the global variable itself : but by locals () acquired "variable dictionary" within the local area , even if it does not affect the local variables modified.

Guess you like

Origin www.cnblogs.com/Gaoqiking/p/11262648.html