程序员

[Python]Namespaces & scope

2016-05-26  本文已影响44人  Iam老J

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:

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

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.
上一篇下一篇

猜你喜欢

热点阅读