【问题标题】:Is the single underscore "_" a built-in variable in Python?单下划线“_”是 Python 中的内置变量吗?
【发布时间】:2010-12-05 01:27:31
【问题描述】:

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

>>> 'abc'
'abc'
>>> len(_)
3
>>> 

【问题讨论】:

标签: python


【解决方案1】:

在标准 Python REPL 中,_ 代表最后一个返回值——在您调用 len(_) 的那一点,_ 是值 'abc'

例如:

>>> 10
10
>>> _
10
>>> _ + 5
15
>>> _ + 5
20

这由sys.displayhook 处理,_ 变量与intsum 之类的东西一起进入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._ 将再次可见)。

【讨论】:

  • 仅供参考:REPL 是 Read-Eval-Print Loop 的缩写。与往常一样,如果您需要,维基百科会提供更多信息。 en.wikipedia.org/wiki/Read-eval-print_loop
  • 什么是“普通标识符”?快速搜索的结果是“仅仅平均;普通;平庸”——这对于 Python 脚本中的“_”意味着什么?
  • 仅供参考 - 注意事项_ 变量应被用户视为只读。不要显式地为其赋值——您将创建一个具有相同名称的独立局部变量,并以其神奇的行为掩盖内置变量。
【解决方案2】:

为什么看不到?在__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 年编辑:我将其称为 “superglobal”,因为 __builtin__ 的成员在任何地方、任何模块中都可用。

【讨论】:

  • 为什么只能在 REPL 中使用而不能在 builtin 中放置的脚本中使用的东西?
【解决方案3】:

通常,我们在 Python 中使用 _ 来绑定一个 ugettext 函数。

【讨论】:

  • 这也是正确的,但仅适用于 Python 应用程序。 gettext.install 将绑定到__builtins__._,因此无需在所有应用程序中导入即可使用;因此是同一种“神奇”的名字。
猜你喜欢
  • 1970-01-01
  • 2022-03-02
  • 2011-08-19
  • 2022-03-02
  • 2019-12-04
相关资源
最近更新 更多