Python --- closures and decorators

1, reference blog: https: //www.cnblogs.com/3me-linux/p/6761635.html

2, closure

def outer():
     x = 1
     def inner():
         print x # 1
     return inner
foo = outer()
foo.func_closure # doctest: +ELLIPSIS
(<cell at 0x: int object at 0x>,)
foo() 
1

Variable scope: the scope of work under the rules of python: "x is a function of a local variable in the outer function when the inner print x # 1 at the time, python interpreter looks for the corresponding variables within the inner, of course. can not be found, then it will look inside the enclosing scope, and will find a match.

Variable life cycle: our variable x is a local variable of the outer function, which means that only when the outer function is running will exist. According to what we know python mode of operation, we can not return after the outer function continues to call the inner function, when the inner function is called, the variable x is long gone, a runtime error may occur. However, it can work

Closure: Python support feature called closure function, the function is defined in a non-nested global scope which can memorize it in which it is closed when the namespace defined. This function can be derived by looking at the conclusion of func_closure property, which contains the value of the property inside the enclosing scope (only contains the value captured, such as x, if the outer which also defines other values, enclosing scope inside It is not there). . . . .

 

3, decorator

 

4、

5、

Guess you like

Origin www.cnblogs.com/hzgq/p/11770315.html