This article mainly introduces the comparison of closures in Python and Javascript. This article explains the closures in Python and Javascript respectively, and makes a simple comparison on their differences, for more information, see the same scripting language. python and Javascript have similar variable scopes. Unlike php, all internal variables of a function are isolated from the outside. that is to say, to process external data, a function must use parameters to pass in the data to be processed (not discussed here using the global keyword). python and Javascript are different. if a variable is declared in a function, it searches the Internet step by step until a value is returned or undefined.
In this case, the closure of python should be very simple. like javascript, we write similar code:
def func1(): a = 1 def func2(): a = a + 1 return a return func2re=func1()print re()print re()
However, the actual situation is that the result does not show 2 and 3 as we expected. Instead, the following error occurs: "UnboundLocalError: local variable 'A' referenced before assignment "(the local variable a is referenced before being assigned a value ). Why is there such a problem? let's first look at how js implements this closure:
《script》 function func1(){ var a=1; function func2(){ a=a+1; return a; } return func2; }re=func1();console.log(re());console.log(re());《script》
As expected, enter 2 and 3. Note the first line of the program. if I add a var above, what is the result of the program running? The final result is that two "NaN" are entered. on Firefox's developer platform, the following description about var is found:
Declares a variable, optionally initializing it to a value.
The scope of a variable declared with var is the enclosing function or, for variables declared outside a function, the global scope (which is bound to the global object ).
Var is used to declare local variables. in the above example, if var a = a + 1 is used, then a is already a local variable in func2, instead of inheriting from func1, the result of NaN is displayed.
Let's go back to the closure of python. the error message means that a is a local variable. In fact, python requires that all the variables on the left of the value assignment statement are local variables, this a is on the left of the equal sign, so it becomes a local variable. as a result, I cannot access a in func1. How can this problem be solved? If it is above python3.0, you can use nonloacal a to specify a as not a local variable before a = a + 1. The nonloacal keyword is not supported in versions earlier than 3.0. we can do this:
def func1(): a = [1] def func2(): a[0] = a[0] + 1 return a[0] return func2re=func1()print re()print re()
As expected, 2 and 3 are printed. From the example of python and Javascript closures, you need to understand the similarities and differences between the variable scopes in python and js variables declaration.