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

按照如下顺序:
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语句用以指明某个特定的变量为封闭作用域,并重新绑定它。

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)

三、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}

关键字local、global和内置函数【locals、globals】的更多相关文章

  1. 【转】Python 内置函数 locals() 和globals()

    Python 内置函数 locals() 和globals() 转自: https://blog.csdn.net/sxingming/article/details/52061630 1>这两 ...

  2. Python两个内置函数——locals 和globals (学习笔记)

    这两个函数主要提供,基于字典的访问局部和全局变量的方式.在理解这两个函数时,首先来理解一下python中的名字空间概念.Python使用叫做名字空间的东西来记录变量的轨迹.名字空间只是一个字典,它的键 ...

  3. Python两个内置函数locals 和globals

    这两个函数主要提供,基于字典的访问局部和全局变量的方式.在理解这两个函数时,首先来理解一下python中的名字空间概念.Python使用叫做名字空间的东西来记录变量的轨迹.名字空间只是一个字典,它的键 ...

  4. Python内置函数locals和globals

    globals()和locals() locals()实际上没有返回局部名字空间,它返回的是一个拷贝.所以对它进行修改,修改的是拷贝,而对实际的局部名字空间中的变量值并无影响. globals()返回 ...

  5. Python内置函数(55)——globals

    英文文档: globals() Return a dictionary representing the current global symbol table. This is always the ...

  6. Python内置函数(26)——globals

    英文文档: globals() Return a dictionary representing the current global symbol table. This is always the ...

  7. [python]locals内置函数

    locals() Update and return a dictionary representing the current local symbol table. Free variables ...

  8. 解读Python中 locals() 和 globals() 内置函数

    首先globals() 和 locals() 是作用于作用域下的内置函数,所以我将它们分为作用域类型的内置函数 1.作用域相关: 1)globals() # 返回全局作用域中的所有名字 2)local ...

  9. Python学习(八) —— 内置函数和匿名函数

    一.递归函数 定义:在一个函数里调用这个函数本身 递归的最大深度:997 def func(n): print(n) n += 1 func(n) func(1) 测试递归最大深度 import sy ...

随机推荐

  1. Python基础——循环语句、条件语句、函数、类

    注:运行环境  Python3 1.循环语句 (1)for循环 注:for i in range(a, b):  #从a循环至b-1 for i in range(n):      #从0循环至n-1 ...

  2. html如何点击子元素事件而不触发父元素的点击事件——阻止冒泡

    如果子元素和父元素都有点击事件,会出现点击事件冒泡的情况. 1.如何避免冒泡: html: <html> <head></head> <body> &l ...

  3. sql过程的条件是IN,用脚本执行

    DECLARE @sql nvarchar(); DECLARE @inStr nvarchar(); SET @inStr='''条件1'',''条件2'''; set @sql='SELECT * ...

  4. XML-RPC-2RPC

    远程过程调用协议 RPC一般指远程过程调用协议 RPC(Remote Procedure Call)—远程过程调用,它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的协议.RPC协 ...

  5. java调用.net的webservice接口

    要调用webservice,首先得有接口,用已经写好的接口地址在myEclipse的目标project中,右键->new web service client-> 选择JAX-WS方式,点 ...

  6. nodejs实现邮件发送

    需要安装的node模块 nodemailer 新建项目目录 mail-test 进入这个项目里使用终端初始化package.json(npm init) 安装express和nodemailer并保存 ...

  7. ifeq ifneq ifdef ifndef

    条件语句中使用到了三个关键字:“ifeq”.“else”和“endif”.其中: 1.        “ifeq”表示条件语句的开始,并指定了一个比较条件(相等).之后是用圆括号括包围的.使用逗号“, ...

  8. Join 和 App

    在关系型数据库系统中,为了满足第三范式(3NF),需要将满足“传递依赖”的表分离成单独的表,通过Join 子句将相关表进行连接,Join子句共有三种类型:外连接,内连接,交叉连接:外连接分为:left ...

  9. springboot和Redis集群版的整合

    此篇接上一个文章springboot和Redis单机版的整合 https://www.cnblogs.com/lin530/p/12019023.html 下面接着介绍和Redis集群版的整合. 1. ...

  10. c# Format() 方法