我刚刚在Python解释器中发现了一些奇怪的东西。让我告诉你:
$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> _
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_' is not defined
>>> 5 + 4
9
>>> _
9
>>> 'Hello world'
'Hello world'
>>> _
'Hello world'
>>> type(3.5)
<type 'float'>
>>> _
<type 'float'>
你可以在翻译中尝试这个;这里没有招数!
最后执行的行的结果是否已分配给名为_
的变量?
有人知道吗?有没有关于它的文件?在哪种情况下它会有用吗?
答案 0 :(得分:6)
看看Reserved identifiers python。
特殊标识符_用于交互式解释器中 存储上次评估的结果;它存储在 内置模块。
此行为也可以在haskell的交互式环境ghci
中找到。而不是_
使用it
。
Prelude> 2+2
4
Prelude> it
4
答案 1 :(得分:2)
在交互式解释器中进行探索时,如果忘记为某些返回的对象指定名称,则可以使用x = _
获取对它的引用。请注意,在ipython
中,对于倒数第二次返回,您还有__
,而___
是倒数第三次。
答案 2 :(得分:0)
这不是一个大秘密(例如,你可以在Code Like a Pythonista中找到它)但是真的,它并不为人所知。当您在命令行中执行大量工作时,它可能很有用。
答案 3 :(得分:0)
每 What is the purpose of the single underscore "_" variable in Python?
_
主要有三种用途。一个是“真实的”(你发现的用法),另外两个是惯例。
有趣......我从来不知道!