关键字local、global和内置函数【locals、globals】
每个函数都有着自已的命名空间,叫做局部名字空间,它记录了函数的变量,包括函数的参数和局部定义的变量。每个模块拥有它自已的命名空间,叫做全局命名空间,它记录了模块的变量,包括函数、类、其它导入的模块、模块级的变量和常量。还有就是内置命名空间,任何模块均可访问它,它存放着内置的函数和异常。
按照如下顺序:
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】的更多相关文章
- 【转】Python 内置函数 locals() 和globals()
Python 内置函数 locals() 和globals() 转自: https://blog.csdn.net/sxingming/article/details/52061630 1>这两 ...
- Python两个内置函数——locals 和globals (学习笔记)
这两个函数主要提供,基于字典的访问局部和全局变量的方式.在理解这两个函数时,首先来理解一下python中的名字空间概念.Python使用叫做名字空间的东西来记录变量的轨迹.名字空间只是一个字典,它的键 ...
- Python两个内置函数locals 和globals
这两个函数主要提供,基于字典的访问局部和全局变量的方式.在理解这两个函数时,首先来理解一下python中的名字空间概念.Python使用叫做名字空间的东西来记录变量的轨迹.名字空间只是一个字典,它的键 ...
- Python内置函数locals和globals
globals()和locals() locals()实际上没有返回局部名字空间,它返回的是一个拷贝.所以对它进行修改,修改的是拷贝,而对实际的局部名字空间中的变量值并无影响. globals()返回 ...
- Python内置函数(55)——globals
英文文档: globals() Return a dictionary representing the current global symbol table. This is always the ...
- Python内置函数(26)——globals
英文文档: globals() Return a dictionary representing the current global symbol table. This is always the ...
- [python]locals内置函数
locals() Update and return a dictionary representing the current local symbol table. Free variables ...
- 解读Python中 locals() 和 globals() 内置函数
首先globals() 和 locals() 是作用于作用域下的内置函数,所以我将它们分为作用域类型的内置函数 1.作用域相关: 1)globals() # 返回全局作用域中的所有名字 2)local ...
- Python学习(八) —— 内置函数和匿名函数
一.递归函数 定义:在一个函数里调用这个函数本身 递归的最大深度:997 def func(n): print(n) n += 1 func(n) func(1) 测试递归最大深度 import sy ...
随机推荐
- google搜索设置,在新的窗口打开
- [转帖]CPU时间片
CPU时间片 https://www.cnblogs.com/xingzc/p/6077214.html CPU的时间片 CPU的利用率好CPU的 load average 是不一样的 Conntex ...
- K8S从入门到放弃系列-(9)kubernetes集群之kubelet部署
摘要: Kubelet组件运行在Node节点上,维持运行中的Pods以及提供kuberntes运行时环境,主要完成以下使命: 1.监视分配给该Node节点的pods 2.挂载pod所需要的volume ...
- Elasticsearch集群搭建笔记(elasticsearch-6.3.0)
# 检查Java版本 java -version # 安装Elasticsearch,所有节点均安装并解压 wget https://artifacts.elastic.co/downloads/el ...
- [tensorflow] 入门day1-数据整理与展示
tensorflow真是一个我绕不开的坑(苍天饶过谁.jpg) 其实tensorflow1和2的差别挺大的,暂时从1入坑,2的话之后简单过一下. tf2中更改的函数(供参考):https://docs ...
- (四)Resquest 知识点总结 (来自那些年的笔记)
目录 URL和URI的区别 获取URL.URI 什么是HttpServletResquest 获取请求头中字段的内容 获取请求信息的数据 将客户机的请求变为一个流返回 常用的方法 request乱码问 ...
- stal 安装
1.1 准备实验环境: 安装系统 1)硬件配置如下 2) 先把光标放到”install CentOS 7”,按 Tab键编辑内核参数,添加 (net.ifnames=0 biosdevname=0) ...
- Python学习笔记——Python 函数
1. 函数定义与调用 def MyFirstFunction(): print('这是我创建的第一个函数') #调用 MyFirstFunction() 这是我创建的第一个函数 2. 函数文档 def ...
- 使用 jsvc 启动tomcat(使用普通用户运行)
使用 jsvc 启动tomcat(使用普通用户运行) jsvc简介 在生产中,tomcat应该以daemon的模式运行,而且如果需要以普通用户的身份启动tomcat,那么就不能使用1024以下的端口, ...
- Django——关于项目开发遇到的一些小技巧
目录 头像图片 js获取网站信息 js获取前端信息 Dj获取刚写入的数据的信息 js跳转新链接 头像图片对象的显示 在做到根据登陆ID决定用户头像的时候,加载静态文件的{% static ‘xxxxx ...