Decorator
Nature # decorator is a function, a function to provide additional functionality (principles: 1 can not modify a function code 2 can not modify a function call, that is a function of how to use the original, decorative finish or how to use)
# = Decorator higher order function + + nested closure function
-----------------------------------------------------------------------
Higher-order functions:
1. reception parameter function is a function name
2. The function return value is a function name
Meet any of the above conditions, that is, higher-order functions
Example 1:
def fun1():
print("fun1")
def test(fun):
fun()
test(fun1)
Example 2:
def fun1():
print("fun1")
def test(fun):
return fun
res = test(fun1)
res()
-----------------------------------------------------------------------
Closure
-----------------------------------------------------------------------
Decorator
Example1:
Time Import
DEF the Timer (Fun):
DEF myRun ():
TIME1 = time.time ()
Fun ()
TIME2 = time.time ()
Print ( "Run Time:", TIME2 - TIME1)
return myRun
@timer do the equivalent of # = the Timer Test (Test)
DEF Test ():
the time.sleep (2)
Print ( 'over RUN')
Test ()
Example2:
Time Import
DEF the Timer (Fun):
DEF myRun (* args, ** kwargs):
TIME1 = time.time ()
RES = Fun (* args, ** kwargs)
TIME2 = time.time ()
Print ( "Run Time: ", TIME2 - TIME1)
return RES
return myRun
@timer equivalent of doing # = Timer Test (Test)
DEF Test (name):
the time.sleep (2)
Print ( 'over RUN')
return 'name:' name +
@ timer # = Timer equivalent of doing test1 (test1)
DEF test1 (name, Age):
the time.sleep (2)
Print ( 'over RUN')
return 'name:' + name + ", Age:" Age +
RES = Test ( 'Saber')
Print (RES)
RES = test1 ( 'Saber', '22 is')
print(res)