Closure
Internal function references to external function scope variables.
Property within the function are all life-cycle, during the execution of all the functions
Closure function in the variable privatized closure, similar to object-oriented
Pictures resolve
Examples of a
https://www.bilibili.com/video/av18586448/?spm_id_from=333.788.videocard.16
DEF FUNC (): # external function A. 1 = # external function scope variables Print ( " the this IS FUNC. " ) DEF func1 (NUM): # internal function is actually a closure function Print ( " the this IS func1 " ) Print (NUM + a) return func1 # function saves the variables a # func () running external functions, internal function was created var = func () # creation process during the execution of func function in # var == func1 var (. 3) # when del var a not exist
Example Two
mylist=[1,2,3,4,5] def func(obj): print('func:',obj) def func1(): obj[0]+=1 print('func1',obj) return func1 var=func(mylist) #var:obj,print('func1',obj)
Decorator
Decorator syntax sugar @
@ func1
DEF FUNC ():
Print ( 'aaa')
does not affect the function of the original function, but also add new features
> @ func1
> DEF the myPrint () ():
the myPrint () () == func2 ( ) + myprint ()
normal decorator zsq (bzs) ()
decorator function parameters: dczsq (cs = 'man' ) (bza) ()
multi-layer packaging the parameters to receive the decoration
are decorated function parameters: just innermost function parameters can be passed
Examples of a
DEF arg_fun (Sex) DEF FUNC (b_func): DEF func2 () IF Sex == ' man ' : Print ( ' you can not have baby ' ) IF Sex == ' Woman ' : Print ( ' You can have baby ' ) return b_func () return func2 return fun1 # arg_func (Sex = 'man') () ()> func1 # func1 ()> func2 # func2 ()> ( '' you can not have baby '') or ( 'you can Health doll ') Arg_fun @ () DEF man (): Print ( ' good work ' ) @ arg_fun () DEF Woman (): Print ( ' good work ' ) man () Woman ()
Example Two
def func1(func) def func2(x,y) print(x,y) x+=5 y+=5 return func(x,y) return func2 @func1 def mysum(a,b) print(a+b) mysum(1,2)
Example Three
import time def display_time(func): def wrapper(*args): t1=time.time() result=func(*args) t2=time.time() print("Total time:{:.4} s".format(t2-t1)) return result return wrapper def is_prime(num) if num<2: return False: elif num==2: return True else: for i in range(2,num): if num%i==0: return False return True @display_time def count_prime_nums(maxnum): count=0 for i in range(2,maxnum): if is_prime(i): count=count+1 return count count=count_prime_nums(10000) print(count)