First, the definition:
is an incoming value is a function, and the return value is also a function of a higher order function.
Second, the role:
Add new functionality without changing the code and invocation of the original function.
Third, examples:
Add two function Earth () and Moon () to print (' They is in the solar system! ')
1, define two functions, each has its own function:
Def earth (): Print (' This was earth! ') def Moon (): Print (' This is moon! ') Earth () Moon ()
Operation Result:
This is earth! This is moon!
The
2, without changing the current function code, and the way in which it is called, adds a function to print the solar system.
def add_func (func): # func is a function body, Func () is the Run function def solar (): print (' it is in the solar system! ') func () return solar # Back to solar function,earth = solar@add_func # This sentence function Func = earthdef earth (): print (' this is earth! ') @add_funcdef moon (): print (' this is moon! ') Earth () Moon ()
Operation Result:
It's in the solar system! This is earth! It's in the solar system! This is moon!
Each call to Earth () and moon () will increase the print it's in the solar system! phrase.
Principle:
and exchange A A value principle is the same, first, the Earth function address is saved to the Func, then the address of solar to the Earth, and then call Earth, the actual operation is solar, and then in the solar call Func, to achieve the original function.
Functions, such as Earth (), without parentheses, can be understood as variable names, with parentheses, running functions, and returning functions to run the results.
3, if the original function with parameters, the innermost func () also need to take parameters.
name = ' Earth ' def Add_func (func): Def solar (): print (' It's in the Solar system! ') Func (name) # with parameter!!!!!!! Print (' 1: ', solar) return solar@add_funcdef Earth (name): # with parameter!!!!!!! Print (' This is%s! '% name) print (' 2: ', Earth) Earth ()
If multiple functions use the same adorner, and the number of these function parameters is different, func () can use the variable-length form func (*args, **kwargs)
This article comes from "Looking back on the empty" blog, so be sure to keep this source http://yishi.blog.51cto.com/1059986/1983475
Python Basics: adorners