Variable acting on

We talked about the scope of functions must introduce the relevant variables.

Is the effective scope of the variables. Variables are not in any position that can be accessed, access rights depending on where the variable is assigned, which is also in the scope.

Generally, in a programming language, code form from the scope of a variable structure, with a block-level ascending levels, functions, classes, modules, packages and the like. But in Python, there is no block-level scope, which is similar to the if block, for a block of statements, with the context manager and so is not present scope of the concept, they are equivalent to ordinary statement.

>>> IF True:             # IF statement blocks no scope 
    X =. 1    
>>> X
 . 1 
>>> DEF FUNC ():          # function scoped 
    A =. 8    
>>> A 
Traceback (MOST Recent Last Call): 
  File " <pyshell. 3 #> " , Line. 1, in <Module1> 
    A 
NameError: name ' A '  IS  Not defined

From the above example, we can find that variables defined in the if statement x, can be accessed externally, but the function FUNC () defined in the variable a, is not accessible externally.

Typically, the internal variables of the function the function can not be accessed externally, but internal access; inner class variables can not be accessed externally, but internal class can. Popular terms, is the internal code can access external variables, external code can not access internal variables.

Scope of a variable determines which part of the program which can access a particular variable name. Python scope a total of four layers, namely:

  • L (Local) local scope
  • E (Enclosing) function outside the closure function
  • G (Global) global scope
  • B (Built-in) built scope
int = X (2.9)   # built scope lookup function int 

global_var = 0   # global scope 
DEF Outer (): 
    out_var =. 1   # functions outer closure function 
    DEF Inner (): 
        inner_var = 2   # local scope

He said earlier the situation was all the variables can be found, that if the variable itself does not define the scope of appear, then how to find it?

Python to L –> E –> G –>Brule find variables, namely: can not find at the local, local will go outside to find a local (eg closures), and then can not find the will to go global to find, and finally to the built-in look. If this can not be found, then an error variable does not exist. For example, the following code inside the function func does not define variables a, but the print function need to print a, how to do that? Looking to the outside! According to L –> E –> G –>Bthe rules, layers of inquiry, this case will soon find from the outer layer to a, and know that it is assigned the value 1, so he printed 1.

a = 1

def func():
    print(a)

Global and local variables

It has a defined function within a local scope variables, called local variables, have global variables defined outside the scope function, is called a global variable. (Classes, modules, etc. Similarly)

The so-called local variable is relative. Local variables external variables may also be variable within a smaller range.

The local variables can be declared within its access function, and can access the global variables in the entire program range. When you call a function, all variables declared within a function name will be added to the scope

A =. 1                # global variable 

DEF FUNC (): 
    B = 2            # the local variable 
    Print (A)         # may access the global variables a, can not access its internal C 

    DEF Inner (): 
        C =. 3        # more local variables 
        Print (A )     # access global variables A 
        Print (B)     # B to the inner function, that external variables 
        Print (C)

global and nonlocal keyword

We look at the following example:

DEF PLUS (arg1, arg2): 
    Total = arg1 + arg2   # Total here is a local variable. 
    Print ( " the function local variable Total =   " , Total)
     Print ( " Total in the function memory address: " , ID ( Total))
     return Total 


PLUS ( 10, 20 is )
 Print ( " external global variables function = Total " , Total)
 Print ( " Total external memory address is a function of: " , ID (Total))

Clearly, plus internal function by total = arg1 + arg2the statement, a new local variable total, and outside its total global variables are two different things. And if we want to modify the outside of the global variables inside a function total it? Use global keywords!

global: specifies the global variables currently use external variables

DEF PLUS (arg1, arg2):
     Global Total 
    Total = arg1 + arg2   # Total here is a local variable. 
    Print ( " the function local variable Total =   " , Total)
     Print ( " Total in the function memory address: " , ID (Total))
     return Total 


PLUS ( 10, 20 is )
 Print ( " external global variables function = Total " , Total)
 Print ( " Total external memory address is a function of: " , ID (Total))

Print result:

Local variables inside a function = 30 Total 
Total address in the memory function is:   1652778112 
function of the external global variable Total = 30 
Total external memory address of a function is:   1652778112

Let's look at the following example:

a =. 1
 Print ( " before the function outer call to the global variable a memory address: " , ID (a)) 


DEF outer (): 
    a = 2
     Print ( " a function outer call to the closure of a variable outside a memory address: " , ID (a)) 

    DEF inner (): 
        a =. 3
         Print ( " after the function inner call closure internal variable a memory address: " , ID (a)) 

    inner () 
    Print ( " after the function inner call, closing a variable external packet memory address: " , ID (a)) 


outer () 
Print ( " function outer finished, a global variable memory address: " , ID (a))

If you have previous knowledge to understand transparent, then there should be no problem, each is a three each of a, each of which has different memory addresses three different variables. Good print results proved this point:

Before the function outer call to the global variable a memory address: 1652777184 
closure when the function outer call to the external variable a memory address:   1652777216 
after the function inner call closure internal variables a memory address:   1652777248 
after the function inner call, the closure external a variable memory address:   1,652,777,216 
function outer finished, the memory address of a global variable:   1652777184

So, if, inner interior that want to use the outer inside a, rather than that of a global variable, how do? With global keyword? Try it first:

 

a =. 1
 Print ( " before the function outer call to the global variable a memory address: " , ID (a)) 


DEF outer (): 
    a = 2
     Print ( " a function outer call to the closure of a variable outside a memory address: " , ID (a)) 

    DEF inner ():
         Global a   # Note that this line 
        a =. 3 Print ( " after the function inner call closure internal variable a memory address: " , ID (a)) 
    inner () Print ( " after the inner call function, the closure of the external memory address of a variable: " , ID (a)) 
outer () Print ( " function outer finished, a global variable memory address: "
        

    


, id(a))

Results are as follows, it is clear that, using the Global global variable a.

Before the function outer call to the global variable a memory address: 1652777184 
closure when the function outer call to the external variable a memory address:   1652777216 
after the function inner call closure internal variables a memory address:   1652777248 
after the function inner call, the closure external a variable memory address:   1,652,777,216 
function outer finished, the memory address of a global variable:   1652777248

then what should we do? Use nonlocalthe keyword! It can be modified nested scopes (the enclosing scope, the outer non-global scope) variables. The global achange nonlocal a, after running to see the results, you can see we really quoted a variable outer function.

Before the function outer call to the global variable a memory address: 1652777184 
closure when the function outer call to the external variable a memory address:   1652777216 
after the function inner call closure internal variables a memory address:   1652777248 
after the function inner call, the closure external a variable memory address:   1,652,777,248 
function outer finished, the memory address of a global variable:   1652777184

Zhenti interview:

Do not test the machine, please state operating results the following code:

a = 10
def test():
    a += 1
    print(a)
test()

a += 1Corresponds a = a + 1, according to the rules assignment operator is to calculate the right a+1. However, Python rule is that if you want to modify a variable inside a function, this variable needs to be an internal variable, unless you use a global statement that it is the external variables. Obviously, we do not define the function of the internal variables a, it will pop up an error before the local variable is not defined on the referenced

More examples:

Look at some examples (in which the closure is to be noted, that the internal function package function):

name = 'jack'

def outer():
    name='tom'

    def inner():
        name ='mary'
        print(name)

    inner()

outer()

The above questions were very simple, because the inner function itself has a variable name, so the print result is mary. Then following it?

name ='jack'

def f1():
    print(name)

def f2():
    name = 'eric'
    f1()

f2()

This question a little confusing, like a long time, it should be 'eric', because when f2 function call inside and call the f1 function, f1 he did not name variables, then out to find, discover f2 defines a name, so I printed the name. wrong! ! ! The result is 'jack'!

Scope Python function depends on its function in the overall position of the block of code in the code, instead of calling time position . When calling f1, f1 body function will be to define the look for the f1 function, its external Shi name ='jack'instead name = 'eric'.

Look at the following example, f2 function returns a function f1

name = 'jack'

def f2():
    name = 'eric'
    return f1

def f1():
    print(name)

ret = f2()
ret()

Consider that the previous example, there are in fact the same purpose, so the result was 'jack'.

Guess you like

Origin www.cnblogs.com/yinluhei/p/11318050.html