Python:_("str")做什么?

Nic*_*ner 8 python syntax

我在Django源代码中看到了这个:

description = _("Comma-separated integers")
description = _("Date (without time)")
Run Code Online (Sandbox Code Playgroud)

它有什么作用?我在Python 3.1.3中尝试它并且它失败了:

>>> foo = _("bar")
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    foo = _("bar")
NameError: name '_' is not defined
Run Code Online (Sandbox Code Playgroud)

2.4.4也没有运气:

>>> foo = _("bar")

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in -toplevel-
    foo = _("bar")
NameError: name '_' is not defined
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?

Mar*_*ers 16

这个名字_和普通名字一样.语法_(x)是调用_使用参数调用的函数x.在这种情况下,它被用作别名ugettext,由Django定义.此函数用于转换字符串.从文档:

指定翻译字符串:在Python代码中

标准翻译

使用函数ugettext()指定转换字符串.将其作为较短的别名_导入是常规,以节省输入.

_在您自己的代码中使用,您可以使用如下导入:

from django.utils.translation import ugettext as _
Run Code Online (Sandbox Code Playgroud)