2012-01-31 184 views
0

我剛剛在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'> 

你可以在你的口譯員試試這個;在這裏工作沒有任何竅門!

最後執行的行的結果是否分配給名爲_的變量?

有人知道嗎?有沒有關於它的文檔?在哪種情況下可能有用?

+2

我想大家都知道(和使用)這...... – JBernardo 2012-01-31 01:37:19

+0

精確複製http://stackoverflow.com/questions/1538832/is-this-single-underscore-a-built-in-variable-in-python – 2012-01-31 01:38:12

+1

我爲什麼被低估? – juliomalegria 2012-01-31 01:38:24

回答

6

看看這裏Reserved identifiers python

特殊標識符_用於交互式解釋器中 存儲最後一次評估的結果;它存儲在 內建模塊中。

此行爲也可以在哈斯克爾的交互式環境ghci上找到。這裏代替_使用it

Prelude> 2+2 
4 
Prelude> it 
4 
0

這不是一個天大的祕密(例如,你可以找到它在Code Like a Pythonista提到),但真實的,它不爲人所熟知。當你在命令行上做了很多工作時,它可能會很有用。

2

在交互式解釋器中進行探索時,當您忘記爲某個返回的對象指定名稱時,可以使用x = _獲取對其的引用。請注意,在ipython中,您還有__爲倒數第二位,而___是倒數第三位。