[英]Is the single underscore “_” a built-in variable in Python?
我不明白这个下划线的含义。 它是一个魔术变量吗? 我在locals()和globals()中看不到它。
>>> 'abc'
'abc'
>>> len(_)
3
>>>
在标准的Python REPL中, _
代表最后返回的值-在您调用len(_)
, _
是值'abc'
。
例如:
>>> 10
10
>>> _
10
>>> _ + 5
15
>>> _ + 5
20
这由sys.displayhook
处理,并且_
变量与int
和sum
类的内容一起进入builtins
名称空间,这就是为什么您无法在globals()
找到它的原因。
请注意,Python 脚本中没有此类功能。 在脚本中, _
没有特殊含义,并且不会自动设置为上一条语句产生的值。
另外,请注意,如果要像上面一样使用,请在REPL中重新分配_
!
>>> _ = "underscore"
>>> 10
10
>>> _ + 5
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
_ + 5
TypeError: cannot concatenate 'str' and 'int' objects
这将创建一个全局变量,该变量将_
变量隐藏在内置变量中。 要撤消分配(并从全局变量中删除_
),您必须:
>>> del _
然后功能将恢复正常( builtins._
将再次可见)。
为什么看不到它? 它在__builtins__
>>> __builtins__._ is _
True
因此,它既不是全球性的也不是地方性的。 1个
这项任务在哪里发生? sys.displayhook
:
>>> import sys
>>> help(sys.displayhook)
Help on built-in function displayhook in module sys:
displayhook(...)
displayhook(object) -> None
Print an object to sys.stdout and also save it in __builtin__.
1 2012 Edit:我将其称为“ superglobal”,因为__builtin__
的成员可以在任何模块的任何地方使用。
通常,我们在Python中使用_绑定ugettext函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.