查看身份验证表单中的一些 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 forgettext()
. 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 importinggettext()
as_()
avoids this problem.
即使这是一个约定,在您的代码中可能并非如此。但请放心,99.9% 的时间 _
是 gettext
的别名 :)
关于Python,括号前的下划线有什么作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20920956/