Comparison of closures in Python and Javascript, pythonjavascript
Similar to scripting languages, 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 of a function, parameters must be used to pass in the data to be processed (the global keyword is not discussed here), while python and Javascript are different. If a function declares a variable, it will search online 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.