python - 对于虚拟变量,__(两个下划线)是否优于 _(一个下划线)?

标签 python naming-conventions

我在 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/

相关文章:

java - AOSP 方法名称结尾

java - 这是正确的命名约定吗?

Python错误: No handlers could be found for logger “xhtml2pdf”

用于扩展另一个产品的 C# 命名空间

Python/Scikit-learn - 线性回归 - 访问线性回归方程

python - 为新数据添加具有唯一标识符的列,但在 python 中维护先前数据的唯一标识符

objective-c - Objective C 中的实例变量/方法参数命名

.net - 通用库的命名空间命名 - 个人名称还是公司名称?

python - 使用 Python 读取 CR2(原始佳能图像) header

python - python切片中 "a[:,1]"的含义是什么