当我在Python shell中输入_
或__
时,会返回一些值。例如:
>>> _
2
>>>__
8
这里发生了什么?
如果您正在使用IPython,则以下全局变量始终存在:
_
(一个下划线):存储先前的输出,就像Python的默认解释器一样。__
(两个下划线):存储上一个先前的输出。___
(三个下划线):存储下一个先前的输出。从IPython文档了解更多内容: 输出缓存系统.
理论上来说,这些只是普通的变量名。按照惯例,单个下划线被用作“不关心”的变量。例如,如果一个函数返回一个元组,而你只对其中一个元素感兴趣,那么在Python中忽略其他元素的方法是:
_, x = fun()
在一些解释器中,_
和 __
有特殊含义,并存储了先前评估的值。
在Python中,它的含义取决于你所指定的含义。下划线是一个有效的名称字符。(但是,如果你使用IPython,请参见Martin的好答案。)
Python 2.7.5 (default, Aug 25 2013, 00:04:04)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
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
>>> _=2
>>> _
2
>>> __
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__' is not defined
>>> __=3
>>> __
3
话虽如此,它们确实具有一些特殊的语义。以单个下划线开头的名称在程序上没有任何不同之处,但按照惯例,这告诉您该名称打算作为私有名称。但是,如果您以两个下划线开头的名称,解释器将对其进行混淆。
>>> class Bar:
... _=2
... __=3
... _x=2
... __x=3
...
>>> y=Bar()
>>> y._
2
>>> y.__
3
>>> y._x
2
>>> y.__x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Bar instance has no attribute '__x'
>>> dir(y)
['_', '_Bar__x', '__', '__doc__', '__module__', '_x']
>>> y._Bar__x
3
_
(一个下划线):存储先前的输出,就像Python默认解释器一样。__
(两个下划线):存储再下一次的先前输出。_iX
,其中X
是输入行号
输出:_X
,其中X
是输出行号
示例:
_
In [1]: 9 * 3
Out[1]: 27
In [2]: _
Out[2]: 27
__
In [1]: 9 * 3
Out[1]: 27
In [2]: 4 * 8
Out[2]: 32
In [3]: __
Out[3]: 27
_iX
In [1]: x = 10
In [2]: y = 5
In [3]: _i1
Out[3]: u'x = 10'
_X
In [1]: x = 10
In [2]: y = 4
In [3]: x + y
Out[3]: 14
In [4]: _3
Out[4]: 14
_
,您可以参考此答案 Python 中的 _。 - Charles0429__name__
时,我得到了'__main__'
。我认为这是全局变量。 - tdolydong