python-name space and scope, closure function, nested function

Source: Internet
Author: User
Tags closure wrapper

First, namespace and scope
Namespace: The place where the name is stored, the exact name space is the place where the name and the variable value are bound. Built-in namespaces: generated at the start of the Python interpreter, storing some python built-in name global namespaces: generated when executing a file, holding the name of the file-level definition X =1deffunc (): Y=2defF1 ():Pass    PrintImportOSclassFoo:PassifX==1:z=3delx Local namespace: During the execution of a file, if a function is called, the local namespace of the function is used to hold the name defined within the function, which takes effect at function invocation and fails the load order after the function call ends: Built- in---"Global---"Local priority Master one: the name of the search order is: local-"Global-"Built-in#max=1deffoo (): Max=2#print (max)foo ()Print(max) x=0defF1 (): x=1defF2 (): x=2deff3 (): X=3Print(X) F3 () F2 ()Print('=f1========', X) F1 ()deffunc1 ():Print('From func1')deffunc1 ():Print('=====?>') func1 () x=1x=10Print(x)
View Code

1. What is a namespace?
#名称空间: The place where the name is stored, three namespaces, (previously the problem x=1,1 stored in memory, where is the name x stored?). Namespaces are where the name X and 1 bindings are stored)
2. Loading order of namespaces
Python test.py#1, the Python interpreter starts first, so the first load is: The built-in namespace # #, executes the test.py file, and then, based on the file, loads the global namespace # #, and if the function is called during the execution of the file, the local namespace is generated temporarily
3, the name of the search order
Local namespace---> global namespace---> Built-in namespaces # Note that the global cannot see local, can see the global in the local, the following example # Max=1def F1 (): #    max=2    def f2 ():        # max=3        Print (max)    F2 () F1 () print (max)
Second, scope
Scope : Extent of action, global scope: Global survival, globally valid: Globals () Max=1111111defF1 ():defF2 ():deff3 ():deff4 ():#print (x)                Print(max) F4 () F3 () F2 () F1 () local scope: temporary survival, partially valid: Locals () x=11111111111111111111111111111111111111111111defF1 (): x=1y=2defF2 ():Pass    #print (Locals ())    Print(Globals ()) F1 ()Print(Locals () isglobals ())Print(Locals ())Print(Dir (Globals () ['__builtins__']))--------------------------------------------------GlobalNonlocal Master:GlobalModify the Global x=1defF1 ():GlobalX explicitly declares that x is the global x, so it changes the global x=1 to local x=2. X=2F1 ()Print(x)-----------------------------------------------L=[]defF2 (): L.append ('F2') can change the value of L directly to ' F2 ', because L is a list and the list is a mutable type. F2 ()Print(L)----------------------------------------------------x=0defF1 ():#x=1    defF2 ():#x=2        deff3 ():#Global xnonlocal x//The x that is directly above the function is modified, and all x is modified to 2. Valid only within the function. X=3f3 ()#print (x)F2 ()Print(x) F1 ()Print(x)-----------------------------------------------------Priority two: The scope relationship, is fixed when the function is defined, regardless of the location of the call, when calling a function, you must return to the original definition of the function to find the scope of the relationship x=1defF1 ():defF2 ():Print(x)returnF2deffoo (func): x=300000func () Res=F1 ()Print(res) func=F1 ()Print(func) x=10000000func () x=10000000deffoo (func): x=300000000func ()#F2 ()x=10000000000000000000000foo (F1 ())#x=10000000000000000000000#foo (F1 ())x=1defF1 ():Globalx x=2F1 ()Print(x)
View Code
#1, Scope        -scoped-global scope (the built-in namespace and the global namespace belong to this scope): Global survival, globally valid     -local scope (local namespace belongs to this scope): Temporary survival, local effective #, scope relationship is fixed in the function definition phase, Regardless of where the function is called, the following X=1def F1 ():    def f2 ():        print (x)    return f2x=100def F3 (func):    x=2    func () x=10000f3 ( F1 ()) #3, view scope: Globals (), locals () LEGB represents the name lookup order: Locals, enclosing function, globals is the namespace within the function, including local variables and formal parameters enclosing the namespace of the outer nested function (common in closures) Globals global variables, the namespace of the module in which the function is defined builtins the namespace of the built-in module
Three Global and Nonlocal keywords   
Global nonlocal Master    : Global Changes the overall x=1def F1 (): Global    x       explicitly declares that x is the global x, so it changes the overall x=1 to local x=2.    x=2f1 () print (x)-----------------------------------------------l=[]def F2 ():    l.append (' F2 ')    Can change the value of L directly to ' F2 ', because L is a list and the list is a mutable type. F2 () print (l)----------------------------------------------------x=0def F1 ():    # x=1    def f2 ():        # x=2        def f3 ():           # Global X           nonlocal x      //modifies the x that is directly above the function, and all x is modified to 2. Valid only within the function.           x=3        f3 ()        # Print (x)    F2 ()    print (x) F1 () print (x)

Four, closed packet function

premise: The scope relationship, when the function is defined, is fixed, regardless of the location of the call, when calling a function, you must return to the location where the function was originally defined to find the scope relationship closure function:1. Functions defined inside a function2. Contains a reference to the outer-role domain name, not a reference to the global role name Word then the intrinsic function is called the closure function x=1defF1 (): x=11111111111defF2 ():Print(x)returnF2func=F1 () x=1000func ()deffoo (): x=12312312312312312312312312312312312313123func () foo ()defdeco (): x=123123123123defwrapper ():Print(x)returnWrapperfunc=deco () func ()#Application of closure function: Lazy calculationImportRequests#PIP3 Install requests installation PIP3defget (URL):returnrequests.get (URL). TextPrint(Get ('https://www.python.org'))Print(Get ('https://www.python.org'))Print(Get ('https://www.python.org'))Print(Get ('https://www.python.org'))defindex (URL):#url= ' https://www.python.org '    defget ():#return Requests.get (URL). Text        Print(Requests.get (URL). Text)returnGetpython_web=index ('https://www.python.org') Baidu_web=index ('https://www.baidu.com') Python_web () baidu_web () name='Egon'defindex (URL): x=1y=2defwrapper ():#x        #y        #return Requests.get (URL). Text        Print(name)returnWrapperpython_web=index ('https://www.python.org')#print (python_web.__closure__[0].cell_contents)Print(Python_web.__closure__)#print (python_web.__closure__[0].cell_contents)#print (python_web.__closure__[1].cell_contents)#print (python_web.__closure__[2].cell_contents)
View CodeFive, nested functions
Nested invocation of a function: in the process of invoking a function, another function called Def Bar ():    print (' from Nbar ') def foo ():                       #再调用一个函数的过程中, another call to the other function    print (' from foo ')    bar () foo ()-----------------------------------------two maximum function def max2 (x, y):    if x > y:        return x    else:        return ydef max4 (a,b,c,d):      maximum value of four values    res1=max2 (A, A,      b) The first result is obtained    res2= Max2 (res1,c)   again, holding this time the results are compared with C    res3=max2 (res2,d)    return res3         get res3 final result print (MAX4 ( 1,2,3,-1))-------------------------------------------------nested definition of a function: Inside a function, define another function Def f2 ():    print (' From F2 ') def F1 ():    the                    name defined inside the X=1 function, only takes effect when the function is called.    # def F2 ()    #     print (' from F2 ')    F2 () F1 ()

  

python-name space and scope, closure function, nested function

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.