Modify Day10 local, global, local variables, the closure function, nested functions

1.locals get all the variables in the current scope

If the function locals outside, acquires locals (return value before printing, all the contents).
# Acquires print return everything before the value 
A = 10 
B = 20 is 
RES = about locals () 
C = 20 is
 Print (RES) 
# built unwritten
# 'A': 10, 'B': 20 is, 'RES': {...}, 'c': 20}
 
If the locals inside the function, before the locals get calls all content
# Get all locals call content before 
DEF FUNC (): 
    F1 =. 11 
    F2 = 12 is 
    RES = locals () 
    F3 = 13 is
     Print (RES) 
FUNC () 
# { 'F2': 12 is, 'F1':. 11}
2.globals get only global variables (global variables, whether only get in and out of function)
globals returns the global namespace of the system dictionary, which put in a global variable space '' '
globals function if the outside, access to globals () return value before printing, all of the content. 
Before globals inside the function if, access to globals call, all content
. 5 = Z1 
Z2 =. 6
 DEF func1 (): 
    F1 =. 1 
    F2 = 2 
    F3 =. 3 
    RES = Globals () 
    F4 =. 6
     Print (RES) 
Z4 =. 8 
func1 () # RES = Globals () 
# built did not give too much the 
# 'Z1':. 5, 'Z2':. 6, 'func1': <0x00000000027E3D08 function func1 AT>, 'Z4':. 8

 

 3. Globals can batch create global variables

DEF FUNC (): 
    RES = Globals ()
     # RES [ 'A1'] =. 1 
    # RES [ 'A2'] = 2 
    for I in Range (. 5 ):
         # Print (I) 
        RES [ " A% D " % ( I)] = I
         '' ' 
        "a% D"% (I) # string formatting 
        
        RES [' A0 '] = 0 
        RES [' A1 ']. 1 = 
        RES [' A2 '] 2 = 
        RES [' A3 '] =. 3 
        RES [' A4 '] =. 4 
        ' ''
        
func()
print(a0)
print(a1)
print(a2)
print(a3)
Print (A4)
 # 0 
# . 1 
# 2 
# . 3 
# . 4 

# about locals for obtaining more variables, globals used to modify some variables more

 

Nested functions

'' ' 
Nested in the outer layer, other than said function 
is nested in the inner layer, the function call it 
' ''

 

Nesting 1:

DEF Outer (): 
    
    DEF inner ():
         Print ( " I am the inner function " ) 
    inner () 
Outer ()
# I inner function

 

Nesting 2:

# Outer function inside outer inner, inner Smaller which also function nested within a call Smaller 
# A =. 17 
DEF outer ():
     # A = 16 
    # ID 99 = 
    DEF Inner ():
         # A = 15 
        DEF Smaller ( ):
             # A = 10 
            Print (the above mentioned id)
             Print ( " I am the smaller function " ) 
        smaller () 
            
    Inner () 
            
            
Outer ()            

 

1.LEGB (find the nearest principle of variable)

'' '     
# Variable find use LEGB principle calling sequence (i.e., the principle of proximity) 
B - the Builtin (Python); Python namespace built-in module (built-scope) (namespace built) 
G - Free Join (Module1) ; namespace where external function (global scope) (global namespace) 
E - Enclosing function about locals; nested functions outside the scope (nested scopes) (local namespace) 
L - the local (function); current scope (local scope) (local namespace) within the function 
according to the principle of proximity, looking up from the lower to outside from the inside 
'' '        

 

# Additional Precautions 
'' ' If, after the pre-existing local variable a, delete it get in get less, 
if the local variable did not previously exist, the default LEGB up in accordance with the principles of order seeking 
' '' 
A = 10
 DEF FUNC (): 
    A 20 is =
     del A
     # Print (A) error 
FUNC ()
 # Print (A)

 

3.nonlocal modify local variables

'' ' 
Nonlocal specifically for modifying local variable 
    (1) which automatically find the local variables used to modify the space on the floor 
    (2) if there is no one on, looking up at the stop 
    (3) could not be found if to a direct error 
'' '

 

(1) nonlocal modified local variables, global variables are not.
If (2) the use of nonlocal can not modify local variables? 
Can.
def outer():
    # a  = 3 
    lst = [1,2,3,4,5]
    def smaller():
        lst[2] += 5
    smaller()
    print(lst)
    
outer()
#[1, 2, 8, 4, 5]

 

# Note point: 
'' ' 
# A = 20 is 
DEF Outer ():     
    A = 81 
    DEF Inner (): 
        Global A 
        A = 16 
        DEF Smaller (): 
            # nonlocal A 
            # Print (A) # Get A 
            # Global A 
            # A + = 3 
            found on a # is a global variable, nonlocal not modify 
            nonlocal a 
            Print (a) 
        Smaller () 
    Inner () 
Outer () 
'' '

 

(3) nonlocal in line with the principle of LEGB

def outer():
    a = 15
    def inner():
        nonlocal a
        a = 17
        print(a)        
    inner()
    print(a)
outer()
# 17
# 17

 

Closure function

'' ' 
Closures: 
    the function uses the local variables of the function, 
    and function to the external function returns out of the closure process is 
    that the function called closure function; 
' ''

 

1. Basic Usage

def outer():
    a = 5
    b = 6
    # inner 是闭包函数
    def inner():
        print(a,b)
    return inner
res = outer()  # res = inner
print(res)
# <function outer.<locals>.inner at 0x0000000001E83D08>
res()          # res() = inner()
# 5 6

 

# Obtain variable __closure__, cell_contents (understand) (or function above the function) function uses closures
RES = TUP. __closure__ 
Print (TUP)
 # (<0x0000000001DF76D8 Cell AT: AT 0x0000000055A46C90 int Object>, <Cell 0x0000000001DF7708 AT: AT 0x0000000055A46CB0 int Object>) 
# obtain a first tuple element inside 
obj = TUP [0]
 Print ( obj)
 # <0x0000000001DF76D8 cell AT: AT 0x0000000055A46C90 int Object> 
# use cell_contents to get the value unit objects among 
RES = obj.cell_contents
 Print (RES)
 # . 5 
obj2 TUP = [. 1 ] 
RES2 = obj2.cell_contents
 Print (RES2)
 # 6

 

 Features closure package

 

# Features Closure: 
"" " 
    use of the function of the local variables of the function, local variables of the function generating function and binding, extend the life cycle of the variable 
    (the actual memory that stores a value, temporarily released ) 
"" "

 

DEF majunqiang_family (): 
    Dajie = " Ma Rong " 
    erjie = " Ma Dongmei " 
    Kuang = " gold " 
    # Money as local variables used in a closure function, then bound and prolong the lifetime of the variable 
    Money = 1000 DEF dajie_hobby (): 
        nonlocal Money 
        Money - = 900
         Print ( " Sister likes to spend money, like buying a Lamborghini, like to buy a bikini, like buying channel, home paying the money remaining d% " % (Money)) DEF erjie_hobby (): 
        nonlocal Money 
        Money = 500 +
         Print (
    
    

    " Sister Ma Dongmei like to make money, like Changchun tie vaccine, because the fake vaccine compensation, like selling blood, 5 dollars a bottle, making money at home d% " % (Money)) 

    DEF Master ():
         # return one yuan group, a tuple in which each element is a function of 
        return (dajie_hobby, erjie_hobby) 
        
    return Master 


FUNC = majunqiang_family () 
TUP = FUNC ()
 Print (TUP)
 # (<majunqiang_family function. <about locals> .dajie_hobby AT 0x0000000001E83D90>, <function majunqiang_family. <about locals> .erjie_hobby AT 0x0000000001E83E18>) 
# Sister function 
Dajie = TUP [0] 
Dajie () 
# sister like spending money, like buying a Lamborghini, like to buy a bikini, like buying channel, paying the rest of the family 100 
# sister function
= TUP erjie [1 ] 
erjie () 
# sister Ma Dongmei like to make money, like Changchun tie vaccine, because the fake vaccine compensation, like selling blood, 5 dollars a bottle, making money at home 600

 

 

Example 2:

def outer(num):
    
    def inner(val):
        return num + val
    return inner
    
func = outer(10)  # func = inner
res = func(21)   # func(21) = inner(21)
print(res)       # res = num + val =  10 + 21 = 31
# 31

 

Closed significance package:

# Simulate a mouse click operation 
# If you are using global variables num to statistics, because the scope is too large, easily lead to unsafe vulnerability. 
Num = 0
 DEF click_num ():
     , Ltd. Free Join num 
    num + = 1
     Print (num)
 # call the function once , accumulating a NUM 
click_num () 
click_num () 
click_num () 

NUM = 100 
click_num () 
click_num () 
# . 1 
# 2 
# . 3 
# 101 
# 102 
# meaning closures: 
'' ' 
closure can preferably used outside the function of the variables, values and closure package plays a protective role in the package can not access the external. 
'' ' 
DEF click_num (): 
    NUM =0
     def func (): 
        nonlocal whether 
        whether the + = 1
         print (whether)
     return func 

click_num = click_num () 
click_num () 
click_num () 
click_num () 
whether = 100 
click_num () 
click_num () 
# 1 
# 2 
# 3 
# 4 
# 5

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/longerandergou/p/10959695.html