我创建了一个简单的代码。 例如
x = 50
def func(x):
x = 2
print 'Changed local x to', x
func(x)
然后我输入 globals() 并期望看到全局变量列表 相反,我得到如下奇怪的输出。为什么?我在 jupyter 中使用 python 2.7。其他一切都很好。而 globals() 的这种行为总是会发生。与 locals() 相同。
{'In': ['',
u"x = 50\n\ndef func(x):\n print 'x is', x\n x = 2\n print 'Changed local x to', x\n\nfunc(x)\nprint 'x is still', x",
u'globals()',
u"x = 50\n\n def func(x):\n x = 2\n print 'Changed local x to', x\n\n func(x)",
u"x = 50\n\ndef func(x):\n x = 2\n print 'Changed local x to', x\n\nfunc(x)",
u'globals()'],
'Out': {2: {...}},
'_': {...},
'_2': {...},
'__': '',
'___': '',
'__builtin__': <module '__builtin__' (built-in)>,
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': 'Automatically created module for IPython interactive environment',
'__name__': '__main__',
'_dh': [u'C:\\Users\\user'],
'_i': u" x = 50\n\n def func(x):\n x = 2\n print 'Changed local x to', x\n\n func(x)",
'_i1': u"x = 50\n\ndef func(x):\n print 'x is', x\n x = 2\n print 'Changed local x to', x\n\nfunc(x)\nprint 'x is still', x",
'_i2': u'globals()',
'_i3': u" x = 50\n\n def func(x):\n x = 2\n print 'Changed local x to', x\n\n func(x)",
'_i4': u" x = 50\n\n def func(x):\n x = 2\n print 'Changed local x to', x\n\n func(x)",
'_i5': u'globals()',
'_ih': ['',
u"x = 50\n\ndef func(x):\n print 'x is', x\n x = 2\n print 'Changed local x to', x\n\nfunc(x)\nprint 'x is still', x",
u'globals()',
u"x = 50\n\n def func(x):\n x = 2\n print 'Changed local x to', x\n\n func(x)",
u"x = 50\n\ndef func(x):\n x = 2\n print 'Changed local x to', x\n\nfunc(x)",
u'globals()'],
'_ii': u" x = 50\n\n def func(x):\n x = 2\n print 'Changed local x to', x\n\n func(x)",
'_iii': u'globals()',
'_oh': {2: {...}},
'_sh': <module 'IPython.core.shadowns' from 'C:\Users\user\Anaconda2\lib\site-packages\IPython\core\shadowns.pyc'>,
'exit': <IPython.core.autocall.ZMQExitAutocall at 0x27d0a90>,
'func': <function __main__.func>,
'get_ipython': <bound method ZMQInteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x0272F9D0>>,
'quit': <IPython.core.autocall.ZMQExitAutocall at 0x27d0a90>,
'x': 50}
最佳答案
您所看到的确实是解释器 session 中定义的全局变量。他们的数量比你想象的要多!这是因为交互式解释器使用一些变量来达到自己的目的,例如跟踪过去的输入和输出。
您看到的一些全局变量(例如 __builtins__
和 exit
)是 Python 语言的记录部分。其他是特定于您的特定解释器或 shell 环境的实现细节,可能会或可能不会记录在任何地方。
至于locals
,它仅在函数内部有用。在模块的顶层,它将返回与 globals
完全相同的字典。 (如果您以交互方式运行它,则包括所有交互式CRUD)。
关于python - python 中 globals() 和 locals() 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38931598/