python中globals()和locals()的奇怪行为

2024-10-02 22:35:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个简单的代码。 例如

x = 50

def func(x):
    x = 2
    print 'Changed local x to', x

func(x)

然后键入globals(),希望看到全局变量列表 相反,我得到了一个奇怪的输出,如下所示。为什么?我在jupyter中使用python2.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}

Tags: tocoreislocaldefipythonndefmodule
1条回答
网友
1楼 · 发布于 2024-10-02 22:35:47

您看到的确实是解释器会话中定义的全局变量。比你想象的还要多!这是因为交互式解释器使用一些变量来实现自己的目的,比如跟踪过去的输入和输出。你知道吗

您看到的一些global(如__builtins__exit)是Python语言的文档化部分。另一些是特定于特定解释器或shell环境的实现细节,可能在任何地方都有文档记录,也可能没有文档记录。你知道吗

至于locals,它只在函数内部有用。在模块的顶层,它将返回与globals完全相同的字典(如果以交互方式运行它,则包括所有交互式crud)。你知道吗

相关问题 更多 >