In "closure", after assigning an external function to a variable, the local variable "becomes" a global variable.

This question comes from the following example of "closure". Let's first guess what the result is.

def funX():
    x = 5
    def funY():
        nonlocal x
        x += 1
        return x

a = funX()
print(a())
print(a())
print(a())

turn out:

6
7
8

You may be wondering, why is this local variable x the same as the global variable? Shouldn't x be reinitialized to 5 every time it is called?

In fact, if you look carefully, you will understand that when a = funX(), as long as the a variable is not reassigned, funX() is not released, which means that the local variable x is not reinitialized.

In order to facilitate understanding, we add another code to the external function: print(x)

def funX():
    x = 5
    print(x)
    def funY():
        nonlocal x
        x += 1
        return x
    return funY

a = funX()
print(a())
print(a())
print(a())

Let's run it again, and the reason why the local variable x "becomes" a global variable appears.

5
6
7
8

If you still don’t understand, if we modify the code again, we will find:

"5" is generated in the process of assigning funX() to variable a.
Let's shorten the sentence:
"5" is generated in the process of assigning funX() to variable a.Assignmentgenerated during the process

That is to say, when the system executes a = funX(), it calls the funX() function, executes the print(x) instruction, and returns the value funY. At this time, the value of a is funY, and the internal function funY() implies conditionsx=5

If funY() is regarded as an independent function, then the process of calling a() three times is equivalent to executing the following instructions:

>>>x = 5
>>>def funY():
        global x
        x += 1
        return x
    return funY

>>>funY()
6
>>>funY()
7
>>>funY()
8

Therefore, the crux of the matter isa = funX() is an assignment process. As long as the a variable is not reassigned, funX() is not released and the local variable x is not initialized to 5.

Guess you like

Origin blog.csdn.net/A_No2Tang/article/details/113785130