The content of this section
- Iterators & Generators
- Decorative Device
- Json & Pickle Data serialization
- Software Catalog Structure specification
- Jobs: ATM Project development
1. Decorator (grammar sugar)
Definition: The essence is a function, (decorating other functions), is to add additional functions for other functions
Principle:
- Cannot modify the source code of the decorated function
- Cannot modify the calling method of the decorated function
Implement the adorner "knowledge" reserve:
1. function is "variable"
2. Higher-order functions
A. Passing a function name as an argument to another function (adding functionality to a decorated function without modifying its source code)
def bar (): print ("in the Bar") def test1 (func): #test1 (bar) print (func) func () #相当于bar () test1 (BAR) # This is equivalent to func=bar--------output--------<function bar at 0x05604300>in the bar
1 Import Time2 defBar ():3Time.sleep (3)4 Print("In the bar")5 defDeco (func):6Start_time=time.time ()7 func ()8Stop_time=time.time ()9 Print("The func run time is%s"% (stop_time-start_time))TenDeco (BAR)#But this example is not appropriate because it changes the way it is called One #Bar () that's the way it used to be called. A -------Output----- - inchThe bar theThe Func run time is3.0007259845733643
Example
B. The return value contains the function name (does not modify the function call method)
1 defBar ():2 Print("In the bar")3 defDeco (func):#Func=bar4 Print(func)#Print bar's memory address5 returnFunc#then return to the memory address of Bar6 #memory address + () to run7 8Deco (BAR)#Pass memory address as function name to Deco9 Print("----Split Line---")Ten Print(Deco (BAR))#print out the return value One Print("------|| ------") ADeco (Bar ())#Pass the return value to Deco, which does not conform to the definition of the higher order function - -----------output------ the<function Bar at 0x058c4228> -----Split Line--- -<function Bar at 0x058c4228> -<function Bar at 0x058c4228> +------|| ------ - inchThe bar +None
View Code
Therefore, you can get the practice without changing the calling method
def bar (): print ("in the Bar") def deco (func): #func =bar Print (func) #打印bar的内存地址 return func #再返回bar的内存地址 #内存地址 + () will be able to run the Bar=deco (bar) #将return返回的值赋值给barbar () #此时bar为内存地址, so bar+ () Can run bar this function------output-----<function bar at 0x05814150>in the bar
3. Nesting functions
Definition: In a function body, use DEF to declare a new function. Instead of calling him.
def foo (): print ("in the Foo") def Bar (): print ("in the bar/") bar () #局部变量只能在局部函数内调用foo () "Def Foo (): bar () #这种是直接调用 "-------output----in the Fooin the bar/
4. High-order function + nested function = = "Adorner"
anonymous functions
Def plus (n): #函数名plus return n+1 plus2 = lambda x:x+1 #没有函数名字, only variable name # but the two get the same result #lambda X:x+1 has a name called Plus2. , equivalent to Def plus2 (x)
Python Road, Day4-python Foundation 4