What is the use of closures in Python?

Source: Internet
Author: User
Tags closure

1, the role of global keywords

If you need to modify global variables in a function, you need to use that keyword, see the example below.

variable=100def  function ():print# does not modify global variables within the function, direct access is no problem, no error #  Output 100
variable=100def  function (): result=variable+111print# does not modify global variables within a function, Direct use is no problem, no error # Output 211

variable=100def  function (): variable+=111print# show local variable ' Variable ' referenced before assignment.  # that is, changing the value of a global variable directly in the function's local scope will cause an error function ()

variable=100def  function (): Variable# at this point the value of modifying the variable variable does not error, The global variable is overwritten because the variable has been redefined within the function's local scope. variable+=111Print# output 1111print# output 100, Although the function internally re-overwrites the variable, but the global variable has not changed, still is

What if we don't re-assign the global variable inside the function and want to change the value of the global variable? This will use the Global keyword, as follows.

variable=100def  function ():Global# uses the global keyword to indicate that variable is global, At this point, you can change the value of variable directly within the function local scope variable+=111print# output 211function ()  Print# output 211, which is not the same as above, found that the global variable variable itself has changed

Summary: The role of Global is to declare a global variable within the function local scope, so that the value of the global variable can be modified inside the function (otherwise only access cannot be modified), and the value of the global variable changed inside the function will change.

2. Function local scope

The local scope of a function is not able to hold information, that is, declaring a variable inside a function after the function call ends, the information stored in the function is destroyed, including the parameters of the function, as follows.

def Fun (step): num=1num+ =Stepprint(num) i=1 while (i<5): Fun (# Continuous Call Function 4 times, the value of each output is 4, that is, 3+1, this means that after each call to the fun function, the function inside the definition of the local variable num is destroyed,# is not saved, Indicates that the local scope of the function was destroyed. What if we want to save the local variables of the function? Introduce "closures". i+=1

3, closures--the essence of the adorner is also closures

The essence of "closure" is the nested definition of a function, which is to define the function inside the function as follows.

There are two different ways of "closure": The first is "call directly" inside the function, and the second is "return a function name".

(1) The first form--direct invocation of

def Maker (name): Num=100def  func1 (weight,height,age): Weight+=1height+=1 age +=1Print(name,weight,height,age) func1 (# internally calls "Intrinsics" Maker directly('  Feifei'# call external function, output Feifei 101 201 301

(2) The second form-returns the name of the function

def Maker (name): Num=100def  func1 (weight,height,age): Weight+=1height+=1 age +=1Print(name,weight,height,age)return# is not called directly here, Instead, it returns the function name (all objects in Python)maker=maker ('feifei'# call wrapper # Calling intrinsic functions

(3) The function of "closure"--saving the state information of functions, so that the local variable information of the function can still be preserved, as follows.

EF Maker (STEP):#Packaging DeviceNum=1defFUN1 ():#intrinsic Functionsnonlocal num#The nonlocal keyword is the same as the previous local, and if you do not use the keyword, the intrinsic function cannot change the value of the external variable.Num=num+step#change the value of an external variable (if you only access external variables, you do not need to apply nonlocal)Print(num)returnfun1#=====================================#J=1Func2=maker (3)#calling an external wrapper while(j<5): Func2 ()#The result of invoking the internal function 4 outputs is 4, 7, 10,J+=1

As can be seen from the above example, the external adorner function local variable num=1, and the call adorner maker (3) when the parameters passed in Step=3 are remembered, so only 1+3=4, 4+3=7, 7+3=10, 10+3=13.

As can be seen here, the maker function is called, but its local variable information is preserved, which is the biggest function of "closure"-Save the local information is not destroyed.

4, the role of nonlocal keyword

The function of this keyword is similar to that of local, which is to allow "intrinsic" to modify the value of the local variable of the "external function (adorner)". Detailed information is not discussed here.

What is the use of closures in Python?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.