[英]weird behaviour of globals() and locals() in python
我创建一个简单的代码。 例如
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}
您所看到的确实是在解释程序会话中定义的全局变量。 他们比您预期的多! 这是因为交互式解释器出于自身目的使用了一些变量,例如跟踪过去的输入和输出。
您所看到的某些全局变量(例如__builtins__
和exit
)是Python语言的记录部分。 其他是特定于您的特定解释器或shell环境的实现详细信息,并且可能会或可能不会在任何地方记录。
对于locals
,它仅在函数内部有用。 在模块的顶层,它将返回与globals
完全相同的字典(如果您以交互方式运行它,则包括所有交互式crud)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.