Python decorator
An adorner is essentially a function that provides additional functionality to other functions without modifying the source code of other functions.
Import Time
def test1 ():
Time.sleep (3)
Print (' In the Test1 ')
Def test2 ():
Time.sleep (3)
Print (' In the Test2 ')
def timer (func): #就是返回deco函数的内存地址
Def deco ():
Stime=time.time ()
Func ()
Ptime=time.time ()
Print (' The Func run time is%s '% (ptime-stime))
Return deco #返回deco函数的内存地址 (function as memory address and parentheses)
Test1=timer (test1)
Test1 ()
Analysis: Test1 memory address (only function name, no parenthesis refers to its memory address) assignment to Func,func () is equivalent to Test1 () run, Deco record test1 () Run related time
Second: higher-order functions
A function is a higher order function if one of the following conditions is met
A function name is passed as a parameter to another
The return value of a function contains n functions, n>0
High-order function demonstration:
| 123456 |
defbar(): print ‘in the bar‘def foo(func): res=func() returnresfoo(bar) |
The beauty of higher-order functions
| 12 456789 |
deffoo(func): return func print ‘Function body is %s‘ %(foo(bar))print ‘Function name is %s‘%(foo(bar).func_name)foo(bar)()#foo(bar)() 等同于bar=foo(bar)然后bar()bar=foo(bar)bar() |
Three: inline functions and variable scopes:
Definition: Create another function inside a function called inline function (based on Python support for static nested fields)
Function Nesting Demonstration:
| 12345678 |
deffoo(): def bar(): print ‘in the bar‘ bar()foo()# bar() |
Access order of local scope and global scope
| 1234567891011 |
x=0defgrandpa(): # x=1 defdad(): x=2 def son(): x=3 printx son() dad()grandpa() |
Effect of local variable modification on global variables
| 12345678910111213141516171819202122 |
y=10# def test():# y+=1# print ydeftest(): # global y y=2 printytest()printydefdad(): m=1 defson(): n=2 print‘--->‘,m +n print‘-->‘,m son()dad() |
Four: Closures:
If in an intrinsic function a reference is made to a variable that is in an outer scope (but not at the global scope), then the intrinsic function is considered closure
| 12345678910111213 |
defcounter(start_num=0): count=[start_num] def incr(): count[0]+=1 returncount[0] returnincr printcounter()printcounter()()printcounter()()c=counter()printc()printc() |
The path to learning in Python Day6