在 Python 中,globals() 和 locals() 是两个内置函数,用于获取全局和局部命名空间中的变量和函数。
globals()函数
globals() 函数返回一个字典,表示当前全局命名空间中的变量和函数。
全局命名空间包含了在当前模块中定义的全局变量和函数,以及导入的模块的全局变量和函数。
可以使用 globals() 函数来查看当前模块中的所有全局变量和函数。
示例:
def my_function():
x = 10
print(globals())
my_function()
输出:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f8fc7bcf940>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'main.py', '__cached__': None, 'my_function': <function my_function at 0x7f8fc7bd0790>}
2. locals() 函数
ocals() 函数返回一个字典,表示当前局部命名空间中的变量和函数。
局部命名空间包含了在当前函数或代码块中定义的变量和函数。
可以使用 locals() 函数来查看当前函数或代码块中的所有局部变量和函数。
示例:
def my_function():
x = 10
y = 20
print(locals())
my_function()
输出:
{'x': 10, 'y': 20}
需要注意的是,globals() 和 locals() 函数返回的字典是只读的,即无法直接修改其中的变量或函数。它们主要用于调试、反射和动态执行代码时的变量和函数检查。
3. 更新操作 update()
update() 是字典对象的方法,用于将一个字典中的键值对更新到另一个字典中。
可以使用 update() 方法将一个字典的内容合并到另一个字典中,或更新一个字典的键值对。
def my_function():
x = 10
y = 20
local_vars = locals()
global_vars = globals()
print("Local Variables:")
print(local_vars)
print("Global Variables:")
print(global_vars)
# 更新全局变量
global_vars.update({'z': 30})
print("Updated Global Variables:")
print(global_vars)
my_function()
输出:
Local Variables:
{'x': 10, 'y': 20}
Global Variables:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f8fc7bcf940>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'main.py', '__cached__': None, 'my_function': <function my_function at 0x7f8fc7bd0790>, 'x': 10, 'y': 20}
Updated Global Variables:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f8fc7bcf940>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'main.py', '__cached__': None, 'my_function': <function my_function at 0x7f8fc7bd0790>, 'x': 10, 'y': 20, 'z': 30}
在上述示例中,首先使用 locals() 和 globals() 函数获取当前函数的局部变量和全局变量。然后,使用 update() 方法将一个新的键值对 ‘z’: 30 添加到全局变量中。打印出更新后的全局变量。
当涉及到 Python 中的 globals()、locals() 和 update() 函数时,可以结合使用它们来实现对全局和局部命名空间的更新。