美文网首页程序员
[Python]Namespaces & scope

[Python]Namespaces & scope

作者: Iam老J | 来源:发表于2016-05-26 17:05 被阅读44次

    Namespaces

    Everything in Python is an object. A name helps Python to invoke the object that it refer to.
    A namespace is a space that holds a bunch of names. Imagine it a 'namespace table' or a 'namespace dictionary'.

    globalNamespace = {x : 1, y : 2, 'return value' : 10}
    

    Note:

    • A module has a global namespace.
    • A class has not a global namespace.
    • Use global to access a global variable in global namespaces

    Scope

    Python searches names in following order, easily remember the sequence as LEGB. Will raise a SyntaxError if not found in those all namespaces.

    
    Local --> Enclosed --> Global --> Built-in
    

    Example 1# Explain the changes in global namespace and function namesapces with scope concept.

    def fun(x, a) : ## 1# funDict = {}, 5# funDict = {x : 3, a : 9}
        y = x + a   ## 6# funDict = {x : 3, a : 9, y : 12}
        return y    ## 7# funDict = {x : 3, a : 9, y : 12, return value : 12}
    
    \#\# main program
    x = 3           ## 2# globalDict = {x : 3}
    z = x + 12      ## 3# globalDict = {x : 3, z : 15}
    a = fun(z, 9)   ## 4# globalDict = {x : 3, z : 15, a : ? } --> 5#,
            ## 8# globalDict = {x : 3, z : 15, a : 12}
    x = a + 7       ## 9# globalDict = {x : 15, z : 15, a : 12}
    

    Example 2# Show how enclosed scope works

    def fun1() :
        def fun2() :
            print ("x inside the fun2 is ", x)
        x = 7
        print ("x inside the fun1 is ", x)
        func2()
    
    x = 5    ## this is a global variable
    print ("x in the main program is ", x)
    fun1()
    
    output:
    
    x in the main program is 5
    x inside the fun2 is 7
    x inside the fun1 is 7
    

    Modules

    • A module is simply a file containing Python code.
    • Each module gets it’s own global namespaces.
    • Each namespace is also completely isolated. Take a prefix to access names in it.
    import SomeModule
    
    SomeModule.method() ## Integer.add()
    
    from SomeModule import SomeName
    method() ## directly call method without module's name, ie. add()
    
    from SomeModule import *
    

    Note:

    1. Everything in Python is an object.
    2. A class has not a global namespace. That's why you need pass an instance as 1st argument and, self required in a class definition.
    3. A module has a global namespace.
    4. It is usually a bad idea to modify global variables inside the function scope.

    相关文章

      网友评论

        本文标题:[Python]Namespaces & scope

        本文链接:https://www.haomeiwen.com/subject/zhdxdttx.html