单个下划线"_"的目的是什么? Python中的变量? [英] What is the purpose of the single underscore "_" variable in Python?
问题描述
这段代码中for
之后的_
是什么意思?
What is the meaning of _
after for
in this code?
if tbh.bag:
n = 0
for _ in tbh.bag.atom_set():
n += 1
推荐答案
_
在Python中有4种主要的常规用法:
_
has 4 main conventional uses in Python:
- 以交互方式保存最后执行的表达式(/语句)的结果 口译会议.此先例是由标准CPython设定的 口译员,其他口译员也纷纷效仿
- 有关在i18n中进行翻译查找的信息(请参阅
gettext
例如文档),如代码所示:
raise forms.ValidationError(_("Please enter a correct username"))
- 作为通用可丢弃"变量名来表示该部分
函数结果的故意被忽略(从概念上讲,它被丢弃了.),如以下代码所示:
label, has_label, _ = text.partition(':')
. - 作为函数定义的一部分(使用
def
或lambda
),其中 签名是固定的(例如通过回调或父类API),但是 这个特定的功能实现不需要所有 参数,如以下代码所示:callback = lambda _: True
- To hold the result of the last executed expression(/statement) in an interactive interpreter session. This precedent was set by the standard CPython interpreter, and other interpreters have followed suit
- For translation lookup in i18n (see the
gettext
documentation for example), as in code like:
raise forms.ValidationError(_("Please enter a correct username"))
- As a general purpose "throwaway" variable name to indicate that part
of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like:
label, has_label, _ = text.partition(':')
. - As part of a function definition (using either
def
orlambda
), where the signature is fixed (e.g. by a callback or parent class API), but this particular function implementation doesn't need all of the parameters, as in code like:callback = lambda _: True
(很长一段时间以来,此答案只列出了前三个用例,但经常出现第四个用例,如
(For a long time this answer only listed the first three use cases, but the fourth case came up often enough, as noted here, to be worth listing explicitly)
后面的丢弃变量或参数名称"用例可能与翻译查找用例冲突,因此有必要避免在也将其用于i18n转换的任何代码块中将_
用作丢弃变量.出于这个原因,人们更喜欢使用双下划线__
作为他们的一次性变量).
The latter "throwaway variable or parameter name" uses cases can conflict with the translation lookup use case, so it is necessary to avoid using _
as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore, __
, as their throwaway variable for exactly this reason).
这篇关于单个下划线"_"的目的是什么? Python中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!