python - 为什么给双下划线 __ 赋值会破坏 ipython 中单下划线 _ 的行为?

标签 python ipython

我一直在玩 output caching system在 IPython 中并注意到一些奇怪的行为,当使用单下划线 _ 获取先前的输出时会产生意想不到的结果。

在写这个问题之前,我不知道 IPython 中实现的输出缓存系统,我想如果我想使用以前的输出,我应该使用双下划线 __ 作为虚拟变量通过访问特殊的 _-Variable。

考虑以下 session :

Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.3.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: 2*3                                                                               
Out[1]: 6

In [2]: 4 + _  # expect 10, OK                                                            
Out[2]: 10

In [3]: __, something = 1, 2                                                              

In [4]: 3*3                                                                               
Out[4]: 9

In [5]: 3 + _  # expect 3+9=12, but:                                                      
Out[5]: 13

正如您在上面看到的,在为 __ 赋值后,使用 _ 并没有给出预期的结果。

阅读之前链接的引用资料后,我知道我可能不应该乱用 ______。分配其中一项是否会卡住所有其他项?
该文档没有暗示这些问题。此外,我发现这非常违反直觉,因为常规 python shell 的行为不同。 (在常规 shell 中完成上述示例后,最终输出符合预期!)

提前感谢您的反馈!

最佳答案

IPython 有(除其他外)3 个特定变量:______, 每次执行死刑时,他们都会四处走动; _ -> __, __ -> ___, ___ -> 丢弃,和最后的结果 -> _

如果这些变量之一被赋值;然后旋转停止。

In [1]: 1
Out[1]: 1

In [2]: 2  # _:1, __:'', ___:''
Out[2]: 2

In [3]: 3  # _:2, __:1, ___:'' 
Out[3]: 3

In [4]: ___ ='something', # _:3, __:2, ___:1

In [5]: __ # still gonna be 2
Out[5]: 2

In [6]: __ # still gonna be 2 again
Out[6]: 2

In [7]: _ # still 3
Out[7]: 3

值得讨论,但很难修改;相对难以弄清楚其含义以及用户是否“修改了”______

在上面的例子中,将 "something" 替换为 1 并且因为 (1 is 1) == True,那么 IPython 不会t“检测”你已经分配了一个下划线并继续移动周围的东西。

关于python - 为什么给双下划线 __ 赋值会破坏 ipython 中单下划线 _ 的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56071832/

相关文章:

python - 在 Numpy 中从一个音高到另一个音高的正弦波滑音

python - 如何摆脱 Python Jupyter notebook 错误 : 404 GET/nbextensions/nbextensions_configurator/tree_tab/main. js

javascript - Bokeh 无法将生成的 HTML 页面加载到浏览器

installation - anaconda 中的 ipython 笔记本命令打开 jupyter 笔记本?

python - ImportError : libgeos-3. 6.2.so:无法打开共享对象文件:没有这样的文件或目录

python - 动态导入模块,然后从所述模块实例化具有特定基类的对象

来自 inode 的 Python 文件名?

python - 在 python 中使用 Beautiful Soup 解析 html

python - 如何删除对象集中的重复项?

python - 使用 IPython 播放音乐时遇到问题