簡體   English   中英

python中globals()和locals()的怪異行為

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM