是单下划线“_"吗?Python中的内置变量? [英] Is the single underscore "_" a built-in variable in Python?

查看:32
本文介绍了是单下划线“_"吗?Python中的内置变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白这个单下划线是什么意思.它是一个神奇的变量吗?我在 locals() 和 globals() 中看不到.

<预><代码>>>>'ABC''ABC'>>>连(_)3>>>

解决方案

在标准 Python REPL 中,_ 代表最后返回的值——在你调用 len(_), _ 是值 'abc'.

例如:

<预><代码>>>>1010>>>_10>>>_ + 515>>>_ + 520

这由 sys.displayhook 处理_ 变量进入 builtins 命名空间,其中包含 intsum 之类的东西,这就是您在 globals().

请注意,Python 脚本中没有这样的功能.在脚本中,_ 没有特殊含义,不会自动设置为上一条语句产生的值.

另外,如果你想像上面那样使用 _ ,请注意在 REPL 中重新分配它!

<预><代码>>>>_ = "下划线">>>1010>>>_ + 5回溯(最近一次调用最后一次):文件<pyshell#6>",第 1 行,在 <module> 中_ + 5类型错误:无法连接str"和int"对象

这会创建一个全局变量,在内置函数中隐藏 _ 变量.要撤消分配(并从全局变量中删除 _),您必须:

<预><代码>>>>德尔_

然后功能将恢复正常(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆