Closure function
What is the function of closure: closure function is a function of nested function objects, namespaces and scope of aggregates.
Closure function must be defined within a function, the closure function name of the function can refer to the outer layer.
Coding _ * _ #: GBK _ * _ # @author: Wonder DEF Outer (): DEF Inner (): # Code body return Inner () Outer () call # closure function
Decorator
What is the decorator : the decorator itself is a function that is without modifying the source code and other functions called by the premise, to increase the functional capabilities of other functions.
Decorator follow the open closed principle. Is added on functional capabilities is open to modifying the function function is turned off.
Why use a decorator: code redundancy to solve problems and improve the scalability of the code.
How to use the decorator: 1, write decorators, 2, call the decorator.
1, the preparation of the decorator
The basic structure of the decorator
wrappper DEF (FUNC): DEF Inner (* args, ** kwargs): before performing be increased functional capabilities # RES = FUNC (* args, ** kwargs) # should be added after the function execution function return RES return Inner
2, call the decorator
wrappper DEF (FUNC):
DEF Inner (* args, ** kwargs):
before performing be increased functional capabilities #
RES = FUNC (* args, ** kwargs)
# should be added after the function execution function
return RES
return Inner
DEF func1 (* args, ** kwargs):
# function body
return func1 = wrappper (func1)
func1 (0,. 1, a = 0, B =. 1) # increase decorator original function call has not changed, there is no source code change
python also provides syntactic sugar structure interpreter, attention must be written decorators front of the object to be decorated. + Decorator function name indicated by the @ symbol
wrappper DEF (FUNC): DEF Inner (* args, ** kwargs): before performing be increased functional capabilities # RES = FUNC (* args, ** kwargs) # should be added after the function execution function return RES return Inner @wrappper func1 DEF (* args, ** kwargs): # function body print ( 'closure') return func1 (0,. 1, a = 0, B =. 1) # increase decorator original function call has not changed, the source the code has not changed