python function scope

Variables can be assigned in three different places
1. If a variable is assigned within def, it is located within this function
2. If a variable is assigned within a nested def, for nested functions, it is non- Local
3. If you assign a value outside def, it is global to the entire file.

Scope rules
1. Embedded modules are global scope
2. The scope of the global scope is limited to a single file
3. Every call to a function is A new local scope is created
4. Variable names assigned in functions are local unless declared as global or non-local
5. All other variable names can be generalized to local, global or built-in inside functions

Any assignment will classify a name as local, including: = statement, module name in import, function name in def, function parameter name, etc. Changing the object inside the
function does not classify the variable as local, if you modify the global list L , L.append('a')

variable name resolution
1. Variable name references are divided into three scopes for query, first local, then the local scope of the upper-level function, then global, and finally built-in
2. By default , variable name assignment will create or change local variables
3. Global declarations and non-local declarations map the assigned variable name to the scope inside the module file

Built-in scope

The built-in scope is a built-in module named builtin, but the built-in scope must be imported before it can be used. The legb law python will automatically search for the module, so you can use built-in variables without importing

The global statement tells python that the function intends to generate one or more global variable names.
The global variable is located at the top level of the module file
. If a global variable is assigned a value within a function, it must
be declared. quote

x=88
def func():
    global x #declare x refers to x outside def
    x=99
func()
print(x) #99

x,y=1,2
def all_global():
    global x #declare x refers to def x, y are also global variables
    x=y+2
all_global()
print(x) #4

#Nested functions, the scope of x is the current function and all nested functions
x=99
def f1():
    x=88
    def f2():
        print(x)
        def f3():
            print(x)
        f3()
    f2 ()
    
f1()

#factory function, a function that remembers the value of a variable in a nested scope, even though that scope may no longer exist
def f3():
    x=88
    def f4():
        print(x)
    return f4

action=f3()
action() #Result: 88, f4 only exists in f3, f4 is no longer active at this time, but still remembers the value of x

def maker(n):
    def action(x):
        return x**n
    return action

f=maker(2)
print(f(3)) #The function action remembers the nested scope variable n, so 3**2=9
g=maker(3)
print(g(3 )) # get a new n

# use default parameters to preserve state of nested scopes

def f5():
    x=88
    def f6(y=x): #The default parameter remembers the x value in f5
        print(y)
    return f6

f=f5()
f()

#Avoid using def nesting, equivalent The function is as follows
def f7():
    x=88
    f8(x)
    
def f8(x):
    print(x)
    
f7()

#Nested scope and lambda
def func():
    x=4
    action=(lambda n:x**n) #lambda can use nested function variable
    return action

action=func()
print(action(2))

def func2 ():
    x=4
    action=(lambda n, m=x:m**n) #default function is used in lambda to remember nested function variables
    return action

action=func2()
print(action(2))

#Scope is compared with default parameters with loop variables
#Nested functions, nested within a loop, and nested functions refer to variables in the upper scope, which are changed by the loop, all generated in this loop The function will have the same value as the value of the referenced variable when the last loop completes

def makeActions():
    acts=[]
    for i in range(5):
        acts.append(lambda x:i**x)
    return acts

acts=makeActions()
print(acts[0](2)) #i=4 4**2=16  
print(acts[1](2)) #i=4 4**2=16
print(acts[ 2](2)) #i=4 4**2=16
print(acts[3](2)) #i=4 4**2=16
print(acts[4](2)) #i=4 4**2=16

#The above program, because the scope of the nested function is searched when it is called, so i=4, so the same i is actually remembered, and the default value parameter must be used to pass
def makeActions ():
    acts=[]
    for i in range(5):
        acts.append(lambda x, i=i:i**x)
    return acts

acts=makeActions()
print(acts[0](2))   #i=0  0**2=0
print(acts[1](2))   #i=1  1**2=1
print(acts[2](2))   #i=2  2**2=4
print(acts[3](2))   #i=3  3**2=9
print(acts[4](2))   #i=4  4**2=16

#nonlocal declares the name to be modified in a nested scope, using the nonlocal statement, the nested def can have read and write access to the name in the nested function
#nonlocal differs from global in that nonlocal applies A name in the scope of a nested function, not all def outside the global module scope
#nonlocal When declaring names, they must already exist in the scope of the nested function - they may only exist in a nested function, and cannot be created by the first assignment in a nested def
# In other words, nonlocal allows assignments to names in the scope of the nested function, and takes the role of such names Domain lookup is limited to nested def, not local scope

def tester(start):
    state=start
    def nested(label):
        nonlocal state #State can be modified, if not declared, state cannot be modified
        state+=1  
        print( label, state)

    return nested

f=tester(0)
f('spam') #state=1, state+=1
f('eggs') #state=2, state+=1

******************************************************************************************

def tester(start):
    global state
    state=start
    def nested(label):
        #nonlocal state #State can be modified, if not declared, state cannot be modified
        global state #At this time, using global in this way can achieve the same effect as nonlocal
        state+ =1  
        print(label, state)

    return nested

f=tester(0)
f('spam') #state=1, state+=1
f('eggs') #state=2, state+=1




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325999405&siteId=291194637