Python,括号前的下划线有什么作用

标签 python syntax

查看身份验证表单中的一些 Django 代码,我注意到以下语法

label=_("Username")

通常我会在字符串周围使用一对引号。有人可以向我解释一下“用户名”周围的下划线和括号的作用吗?

最佳答案

_ 是可调用的名称(函数,callable object)。它通常用于 gettext 函数,for example in Django :

 from django.utils.translation import gettext as _
 print _("Hello!")  # Will print Hello! if the current language is English
                    # "Bonjour !" in French
                    # ¡Holà! in Spanish, etc.

正如文档所说:

Python’s standard library gettext module installs _() into the global namespace, as an alias for gettext(). In Django, we have chosen not to follow this practice, for a couple of reasons:

[...]

The underscore character (_) is used to represent “the previous result” in Python’s interactive shell and doctest tests. Installing a global _() function causes interference. Explicitly importing gettext() as _() avoids this problem.

即使这是一个约定,在您的代码中可能并非如此。但请放心,99.9% 的时间 _gettext 的别名 :)

关于Python,括号前的下划线有什么作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20920956/

相关文章:

Python:从 Web 界面运行时导入其他 python 文件

matlab - fopen ('text.txt' , 'wt' ) 在 MATLAB 中是什么意思?

python - 子进程返回退出状态 1

python - 使用 BeautifulSoup 提取图像链接

mysql - COUNT(DISTINCT(CASE WHEN 寻找函数而不是列?MySQL

javascript - 如何通过 jquery 中的点击事件切换 ids?

css - * HTML Body 在 css 样式表中是什么意思?

python - 新的 python async 和 await 关键字

python - Celery 将命令行参数传递给 Task

javascript - 字典数据 ito d3 折线图 - 服务器端的 Django Python