在Python中,它意味着你告诉它的意思。下划线是名称中的有效字符。(但是,如果您使用的是IPython,请参见Martin's fine answer。)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 "", line 1, in
NameError: name '_' is not defined
>>> _=2
>>> _
2
>>> __
Traceback (most recent call last):
File "", line 1, in
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 "", line 1, in
AttributeError: Bar instance has no attribute '__x'
>>> dir(y)
['_', '_Bar__x', '__', '__doc__', '__module__', '_x']
>>> y._Bar__x
3