This paper starts from the following aspects to learn more about python function:
- The function of variable scope
- Closures phenomenon in the function
- Function decorator
- Standard library decorator
- Superposition decorator
- Parametric Decorator
def A(func):
def B():
return
return B
LEGB principle function of: the local scope -> External Scope -> global scope -> this can be a ...
For the function B function body B is called local scope, function A body called the outer scope of B, where A file is of global scope B
If you need to make changes in the global variables q B, please use the global keyword to declare variables
Function closure:
For the body B can call the function variable c in A defined scoping behavior is called closure criteria: a function in a non-global scope able to remember it was named the closed space (B enclosed in A)
Wherein the variables called a free variable Cc: unbound variable domain refers to the local action q using nonlocal variables to declare a free (as global)
Decorator:
Definition: to enhance the function of the behavior of another function execution l before the objective function objective function is modified
Performance: ex is shaped like a decorator
Use: @A
def target():
pass
Parameterized decorator: the decorator know the objective function accepts a function name as a parameter is passed, then how do garnished if the objective function with parameters?
A layer outside the decorator nested function, the objective function to the processing parameters of the problem
def add(*args,**kwargs):
def A(func):
def B(*args,**kwargs):
return res
return B
return A
Wherein the add function g c factory function call, the parameters dedicated to handling the objective function
Standard library decorator:
functools.lru_cache lru_cache which is least recently used for a function recently executed to make a record to avoid duplication of execution
Memo function is to greatly simplify the running time
Single-point distribution functools.singledispatch d
This design is also reflected in the z mode and REST frameworkz Djangoh mode of CBV
The set of functions to perform the same type of the first parameter in different ways
(Multiple dispatch: selecting a plurality of parameters according to specific functions)