2019年11月18日 / 499次阅读 / Last Modified 2021年1月7日
内置函数
globals()函数和locals()函数都是python的内置函数,他们的作用分别是以dict数据类型返回python程序的全局变量和某个局部的变量。globals()可读可写,而locals()是只读!
C:\Users\xinli>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': , '__spec__': None, '__annotations__': {}, '__builtins__': }
>>>
>>> a = 1
>>> b = 2
>>> import os
>>> import sys
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': , '__spec__': None, '__annotations__': {}, '__builtins__': , 'a': 1, 'b': 2, 'os': , 'sys': }
>>>
globals()函数可读可写是什么意思?请看下面代码:
>>> a
1
>>> def ca():
... globals()['a'] = 2
...
>>> ca()
>>> a
2
在函数ca中,直接修改globals()函数返回的dict对象,是可以的。不过,建议不要这样使用!而是采用global申明的办法。
locals()函数就是把调用时的局部变量以dict对象的方式返回,locals()返回的内容只读,不能像globals()函数那些可写。
>>> def cb():
... print(locals())
... a = 1
... b = 3
... c = 5
... import time
... print(locals())
...
>>> cb()
{}
{'a': 1, 'b': 3, 'c': 5, 'time': }
定义了一堆局部变量后(包括import的模块),再使用locals(),就能看到这些对象了。
个人认为,globals()和locals()这两个函数,在调试python代码的时候,会比较有用,还有就是作为别的工具的输入,比如eval函数。
下面这个例子,说明了不要通过locals()返回的dict对象进行写动作:
>>> def cb():
... print(locals())
... locals()['a'] = 1
... print(locals())
... print(a)
...
>>> cb()
{}
{'a': 1}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in cb
NameError: name 'a' is not defined
locals()只是个代理,让你能看到局部空间内的东西,但是不要去写,写完了也访问不了!(这个问题的具体原因,就要去看python源码了)
-- EOF --
本文链接:https://www.pynote.net/archives/1510
《globals()函数和locals()函数》有3条留言
©Copyright 麦新杰 Since 2019 Python笔记
python官方对locals()函数有一段说明:The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter. [ ]
下面的用法是错误的:
[ ]判断某个变量是否已经存在,可以使用这两个函数。 [ ]