是单下划线“_"吗?Python中的内置变量? [英] Is the single underscore "_" a built-in variable in Python?
问题描述
我不明白这个单下划线是什么意思.它是一个神奇的变量吗?我在 locals() 和 globals() 中看不到.
<预><代码>>>>'ABC''ABC'>>>连(_)3>>>在标准 Python REPL 中,_
代表最后返回的值——在你调用 len(_)
, _
是值 'abc'
.
例如:
<预><代码>>>>1010>>>_10>>>_ + 515>>>_ + 520这由 sys.displayhook
处理,_
变量进入 builtins
命名空间,其中包含 int
和 sum
之类的东西,这就是您在 globals()中找不到它的原因代码>.
请注意,Python 脚本中没有这样的功能.在脚本中,_
没有特殊含义,不会自动设置为上一条语句产生的值.
另外,如果你想像上面那样使用 _
,请注意在 REPL 中重新分配它!
这会创建一个全局变量,在内置函数中隐藏 _
变量.要撤消分配(并从全局变量中删除 _
),您必须:
然后功能将恢复正常(builtins._
将再次可见).
I don't understand what this single underscore means. Is it a magic variable? I can't see it in locals() and globals().
>>> 'abc'
'abc'
>>> len(_)
3
>>>
In the standard Python REPL, _
represents the last returned value -- at the point where you called len(_)
, _
was the value 'abc'
.
For example:
>>> 10
10
>>> _
10
>>> _ + 5
15
>>> _ + 5
20
This is handled by sys.displayhook
, and the _
variable goes in the builtins
namespace with things like int
and sum
, which is why you couldn't find it in globals()
.
Note that there is no such functionality within Python scripts. In a script, _
has no special meaning and will not be automatically set to the value produced by the previous statement.
Also, beware of reassigning _
in the REPL if you want to use it like above!
>>> _ = "underscore"
>>> 10
10
>>> _ + 5
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
_ + 5
TypeError: cannot concatenate 'str' and 'int' objects
This creates a global variable that hides the _
variable in the built-ins. To undo the assignment (and remove the _
from globals), you'll have to:
>>> del _
then the functionality will be back to normal (the builtins._
will be visible again).
这篇关于是单下划线“_"吗?Python中的内置变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!