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

按照如下顺序:
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. webstorm对引入的css资源进行提示

  2. [转帖]持久化journalctl日志清空命令查看配置参数详解

    持久化journalctl日志清空命令查看配置参数详解 最近 linux上面部署服务 习惯使用systemd 进行处理 这样最大的好处能够 使用journalctl 进行查看日志信息. 今天清理了下 ...

  3. Redis部分

  4. SSH简介及两种远程登录的方法

    出处 https://blog.csdn.net/li528405176/article/details/82810342 目录 SSH的安全机制 SSH的安装 启动服务器的SSH服务 SSH两种级别 ...

  5. WUSTOJ 1291: 2n皇后问题(Java)

    题目:

  6. SVN迁移到Gitlab实践经历

    svn 迁移至git操作手册 项目交付.版本管理工具变更等情况下,迁移svn旧历史记录有很大必要,方便后续追踪文件的提交历史,文件修改记录比对等.git自带了从svn迁移至git的工具命令,可很好的对 ...

  7. (转) 从0移植uboot(五) _实现串口输出

    ref : https://www.cnblogs.com/xiaojiang1025/p/6500520.html 串口作为一种非常简单的通信方式,才是嵌入式系统调试的王道,通过设置串口输出,我们可 ...

  8. Python+Appium启动手机APP或者浏览器

    一.设备信息配置 脚本如下: from appium import webdriver class my_app(): def __init__(self): desired_caps = {} # ...

  9. MySQL 多列排序

    MySQL 基础篇 三范式 MySQL 军规 MySQL 配置 MySQL 用户管理和权限设置 MySQL 常用函数介绍 MySQL 字段类型介绍 MySQL 多列排序 MySQL 行转列 列转行 M ...

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

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