每个函数都有着自已的命名空间,叫做局部名字空间,它记录了函数的变量,包括函数的参数和局部定义的变量。每个模块拥有它自已的命名空间,叫做全局命名空间,它记录了模块的变量,包括函数、类、其它导入的模块、模块级的变量和常量。还有就是内置命名空间,任何模块均可访问它,它存放着内置的函数和异常。

按照如下顺序:
1、局部命名空间 - 特指当前函数或类的方法。如果函数定义了一个局部变量,Python将使用这个变量,然后停止搜索。

2、全局命名空间 - 特指当前的模块。如果模块定义了一个变量,函数或类,Python将使用这个变量然后停止搜索。

3、内置命名空间 - 对每个模块都是全局的。作为最后的尝试,Python 将假设 x 是内置函数或变量。

一、global关键字

这是从官网上抄的一句话。

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. 
It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global. Names listed in a global statement must not be used in the same code block textually preceding that global statement. Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement.

global语句是适用于当前整个代码块的声明。它是全局变量的标识符,如果某名字在局部名字空间中没有定义, 就自动使用相应的全局名字。

没有global是不可能手动指定一个名字是全局的.在 global 中出现的名字不能在global 之前的代码中使用.

在 global 中出现的名字不能作为形参, 不能作为循环的控制对象, 不能在类定义, 函数定义, import语句中出现.

VS 如果某名字在局部名字空间中没有定义, 就自动使用相应的全局名字

a=1

def fun():
    print(a)
fun()
结果:1

VS 如果某名字在局部名字空间中没有定义, 就自动使用相应的全局名字,但是不能做修改

a=1
def fun():
    a=a+1
    print(a)
fun()
UnboundLocalError: local variable 'a' referenced before assignment

VS  在 global 中出现的名字不能在global 之前的代码中使用

a=1
global a
SyntaxError: name 'a' is assigned to before global declaration

VS  没有global是不可能手动指定一个名字是全局的

a=1

def fun():
    global a
    a+=1
    print(a)
fun()
结果:2

VS 没有global是不可能手动指定一个名字是全局的

a=1

def fun(a):
    a+=1
    print(a)
fun(a)
print(a)
结果:2
     1

 

二、local关键字

 nonlocal语句用以指明某个特定的变量为封闭作用域,并重新绑定它。 

关键字local、global和内置函数【locals、globals】_python

 关键字local、global和内置函数【locals、globals】_局部变量_02

 

 

def scope_test():
    def do_local():
        spam = "local spam"

    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"

    def do_global():
        global spam
        spam = "global spam"

    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)


scope_test()
print("In global scope:", spam)

关键字local、global和内置函数【locals、globals】_作用域_03

 

 

三、globals() :返回当前作用域内全局变量的字典

>>> globals()
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}
>>> a = 1
>>> globals() #多了一个a
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, 'a': 1, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}

四、locals() 函数功能返回当前作用域内的局部变量的字典

>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, ]

'__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>} >>> >>> a=1 >>> locals() {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>,

'__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 1} >>> globals() {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 1} >>>

 

 案例:

def fun():
    print("before define local a:","\n",locals())
    print("*"*40)
    a=1
    print("after define local a:", "\n", locals())
    print("*"*40)

print("before define global a:","\n",globals())
print("*"*40)
b=1
fun()
print("after define global a:","\n",globals())

 

before define global a: 
 {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f76dfa3f198>, 

'__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'test.py', '__cached__': None, 'fun': <function fun at 0x7f76dfaebe18>} **************************************** before define local a: {} **************************************** after define local a: {'a': 1} **************************************** after define global a: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f76dfa3f198>,
'__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'test.py', '__cached__': None, 'fun': <function fun at 0x7f76dfaebe18>, 'b': 1}

 

大多数人都以为是才智成就了科学家,他们错了,是品格。---爱因斯坦