Python closure implementation

introduction

        The concept of closure is widely used. In Javascript, Perl is used in many occasions, of course, Python also has the implementation of closures. The following is my own understanding. The closure refers to the definition of a function inside the function, which uses the variables of the outer function, so that the variables used are not cleared when the inner function ends (for the inner function, it is a local variable). The advantage of this is that you can Logically modify global variables. Here is a brief introduction to perl. Closures in perl are mainly used for object-oriented, which realizes the encapsulation of data.

Code 1:

def  f():
    count=0 #declare count variable
    def wrap():
        count+=1 #Count plus 1
        return count #return value
    return wrap returns the function address

f1=f() #Call the f() function and return a wrap function address
f() #call wrap() function
f() #call wrap() function
f() #call wrap() function

The result is an error: 


It turns out that global variables can be accessed freely in Python syntax, but it is not possible to modify global variables. If you want to modify it, you need to declare it as a list type.

Because when python calls a variable internally, it is processed according to the declaration. If the variable is operated at this time, an error of no assignment will be reported.

Code 2:

def  f():
    count=[0] #Declare a count variable, which is modified to a list type here
    def wrap():
        count[0]+=1 #Count plus 1
        print count[0] #return value
    return wrap returns the function address

f1=f() #Call the f() function and return a wrap function address
f() #call wrap() function
f() #call wrap() function
f() #call wrap() function

result execution


        This is to implement a simple closure function, making the function similar to a class, with object-oriented properties. In addition to the above invocation method, decorators can also be used to simplify.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325647631&siteId=291194637