Python 全局命名空间值

问题描述 投票:0回答:2

我只是好奇,我最近才了解到解释器用来引用对象的Python内置、全局和本地命名空间基本上是一个Python字典。

我很好奇为什么当调用

global()
函数时,字典会打印字符串中的变量对象,但定义的函数中的对象引用硬件内存地址?

例如-

这个脚本:

print("Inital global namespace:")
print(globals())

my_var = "This is a variable."

print("Updated global namespace:")
print(globals())

def my_func():
        my_var = "Is this scope nested?"

print("Updated global namespace:")
print(globals())

输出:

Inital global namespace:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10a483208>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'global_check', '__cached__': None}
Updated global namespace:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10a483208>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'global_check', '__cached__': None, 'my_var': 'This is a variable.'}
Updated global namespace:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10a483208>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'global_check', '__cached__': None, 'my_var': 'This is a variable.', 'my_func': <function my_func at 0x10a40ce18>}

'my_var': 'This is a variable.', 'my_func': <function my_func at 0x10a40ce18>

我理解有些人可能认为这类事情并不重要,但如果我想查看函数的对象,我是否能够做这样的事情?这个问题有意义吗?

python scope namespaces
2个回答
2
投票

当您在代码中键入

my_var
时,Python 需要知道它代表什么。首先,它会检查
locals
,如果没有找到引用,则会检查
globals
。现在,当您编写
'string' == my_var
时,Python 可以评估您的代码。同样,当您在代码中编写函数名称时,Python 需要知道它代表什么。由于函数的输出可以根据输入而变化,因此 Python 无法存储像字符串这样的简单值来表示
globals
中的函数。相反,它存储内存引用,以便当您输入
my_func()
时,它可以转到该内存存储并使用该函数来计算输出。


0
投票

使用

global my_var
然后您可以在本地命名空间中分配全局变量

© www.soinside.com 2019 - 2024. All rights reserved.