我在 Python 2.7 中有一个任意示例,我需要一个虚拟变量。我发现很多资源都推荐使用单个 _
,例如下面的示例:
directory = {key: [0 for _ in range(catnum)] for key in register}
我找到了这个链接:http://docs.python-guide.org/en/latest/writing/style/#create-an-ignored-variable
这是从上述 URL 中引用的一段话:
Note: Many Python style guides recommend the use of a single underscore _ for throwaway variables rather than the double underscore __ recommended here. The issue is that _ is commonly used as an alias for the gettext() function, and is also used at the interactive prompt to hold the value of the last operation. Using a double underscore instead is just as clear and almost as convenient, and eliminates the risk of accidentally interfering with either of these other use cases.
我刚开始用 Python 编码,想知道 __
是否是公认的约定? _
会导致问题的代码示例是什么?
directory = {key: [0 for __ in range(catnum)] for key in blasts}
最佳答案
好吧,引用的段落告诉你在哪里使用 _
将是一个问题:在交互式解释器中,以及在使用它作为 gettext.gettext
的别名的任何代码中,这在希望将其文本本地化的应用程序中很常见。这是 gettext.gettext
的文档(强调我的):
Return the localized translation of message, based on the current global domain, language, and locale directory. This function is usually aliased as _() in the local namespace.
大多数程序使用 gettext.gettext
像这样:
import gettext
gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
gettext.textdomain('myapplication')
_ = gettext.gettext
# ...
print _('This is a translatable string.')
这样你实际上不必输入 gettext
任何你想要可翻译字符串的地方。
现在,说了这么多,我明白了 for _ in range(catnum)
远远超过我看到的for __ in range(catnum)
.我想你知道如果使用 _
会引起问题;要么你知道你在解释器中工作,要么你知道你的应用程序使用 _
作为gettext.gettext
别名。使用 __
不过,绝对更安全。
如果我猜为什么它没有流行起来,我会说也许人们只是被 __
推迟了。因为双下划线与 Python 的名称困惑的“私有(private)”变量相关联,社区通常不赞成认为没有必要。不过,这只是一个猜测。
关于python - 对于虚拟变量,__(两个下划线)是否优于 _(一个下划线)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24984349/