将添加有关 Jupyter 笔记本的更多信息。 Jupyter notebook 只是iPython 交互式内核的视觉包装。当您在其中一个笔记本单元格中的函数或类之外声明变量时,它会自动成为可以访问的全局变量,如this answer 中所述。如果你在 notebook 中运行 globals() 函数,你会发现情况确实如此
Python 3.8.6 (default, Sep 30 2021, 09:13:34)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.26.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: test = 'x'
In [2]: def test_func():
...: print(test)
...:
In [3]: test_func()
x
In [4]: globals()
Out[4]:
{'__name__': '__main__',
'__doc__': 'Automatically created module for IPython interactive environment',
'__package__': None,
'__loader__': None,
'__spec__': None,
'__builtin__': <module 'builtins' (built-in)>,
'__builtins__': <module 'builtins' (built-in)>,
'_ih': ['',
"test = 'x'",
'def test_func():\n print(test)\n ',
'test_func()',
'globals()'],
'_oh': {},
'_dh': ['/Users/matthewbarlowe/code/javascript/beard'],
'In': ['',
"test = 'x'",
'def test_func():\n print(test)\n ',
'test_func()',
'globals()'],
'Out': {},
'get_ipython': <bound method InteractiveShell.get_ipython of <IPython.terminal.interactiveshell.TerminalInteractiveShell object at 0x110896610>>,
'exit': <IPython.core.autocall.ExitAutocall at 0x11089a640>,
'quit': <IPython.core.autocall.ExitAutocall at 0x11089a640>,
'_': '',
'__': '',
'___': '',
'_i': 'test_func()',
'_ii': 'def test_func():\n print(test)\n ',
'_iii': "test = 'x'",
'_i1': "test = 'x'",
'test': 'x',
'_i2': 'def test_func():\n print(test)\n ',
'test_func': <function __main__.test_func()>,
'_i3': 'test_func()',
'_i4': 'globals()'}
关于不使用全局变量的所有建议都很好,但是在进行探索性数据分析时(这是 Jupyter 笔记本的主要用例),如果您不使用全局变量,则以这种方式使用全局变量是完全可以接受的生产中的代码。一旦你需要自动化,你应该正确地确定你的变量范围。