Closures breakthrough scope

1  '' ' 
2  concepts: internal function defined functions in the body, and the internal variable external function uses a function,
 3  external function will return the value as a function of an internal return, the internal function is called closures.
. 4  
. 5  advantages: avoiding polluting the global environment variables, local variables we can indirectly use globally.
6  Disadvantages: long-term data will reside in memory, resulting in a waste of memory, in the IE browser, easily collapse,
 7  so please use caution.
8  '' ' 
9  # closure: a function within the defined functions, and external function returns a function of the internal function name, 
10  # in this way can be called closure. 
11  # a function returns a function ---- closure 
12 is  DEF Outer ():
 13 is      Print ( " Outer executed " )
 14      DEF Inner ():
 15          Print ( " Inner performed" )
 16      return Inner
 . 17  
18 is RES = Outer ()    # RES Outer == () == Inner 
. 19  RES ()
 20 is  # integrated written 
21 is  Outer () ()
 22 is  
23 is  DEF Outer ():
 24      Print ( " 123 " )
 25      DEF inner ():
 26 is          Print (456 )
 27          return  " heihei " 
28      # actual return is: return value of the internal function 
29      return inner ()
 30 RES = Outer ()
31 is  Print (RES)
 32  
33 is  #
 34 is globalA = 100 # globally 
35  DEF Closer ():
 36      eB = 200 is   # closure scope 
37 [      DEF Inner ():
 38 is          iC = 300    # local 
39          return iC
 40      return Inner
 41 is  
42 is RES Closer = ()    # RES === Inner 
43 is A = RES ()             # RES () Inner ==== () 
44 is  Print (A)
 45  
46 is  
47  
48 #
49 def outer():
50     num = 666
51     def inner():
52         nonlocal num
53         num += 1
54         return num
55     return inner
56 res = outer()   # res == inner
57 a = res()
58 print(a)  # 667
59 b = res()
60 print(b)  # 668
61 print(res())   # 669
62 
63 print(outer()())   # 667
64 print(outer()())   # 667
65 print(outer()())   # 667
66 
67 # for i in range(3):   # i=0   1
68 #     num = 2
69 #     for j in range(3):  # j=0  1  2
70 #         num += 1
71 #         print(num)  # 3  4  5
72 #     print(num)  # 5

 

Guess you like

Origin www.cnblogs.com/BKY88888888/p/11266127.html